对于编写多线程的朋友来说,线程互斥是少不了的。在linux下面,编写多线程常用的工具其实 是pthread_mutex_t。本质上来说,它和Windows下面的mutex其实是一样的,差别几乎是没有。 希望对线程互斥进行详细了解的朋友可以看这里。 - #include
- #include
- #include
- #include
-
- static int value = 0;
- pthread_mutex_t mutex;
-
- void func(void* args)
- {
- while(1)
- {
- pthread_mutex_lock(&mutex);
- sleep(1);
- value ++;
- printf("value = %d!\n", value);
- pthread_mutex_unlock(&mutex);
- }
- }
-
- int main()
- {
- pthread_t pid1, pid2;
- pthread_mutex_init(&mutex, NULL);
-
- if(pthread_create(&pid1, NULL, func, NULL))
- {
- return -1;
- }
-
- if(pthread_create(&pid2, NULL, func, NULL))
- {
- return -1;
- }
-
- while(1)
- sleep(0);
-
- return 0;
- }
|