POSIX线程同步

来源:互联网 发布:js同时获取多个id 编辑:程序博客网 时间:2024/06/03 22:39

在posix编程中,如果在不同的线程中几乎同一时间操作同一个变量的时候,就会出现不同步。

如何解决这样的问题,这里需要用到互斥量,互斥锁的概念。请看UNIX环境高级编程P299页

#include <stdio.h>#include <unistd.h>#include <pthread.h>//线程1 void *thread_func1(void *arg);//线程2 void *thread_func2(void *arg);pthread_mutex_t lock ;int count = 0 ;int main(void){pthread_t  tid1,tid2 ;pthread_create(&tid1 , NULL , thread_func1 , 0);pthread_create(&tid2 , NULL , thread_func2 , 0);//互斥锁初始化 pthread_mutex_init(&lock , NULL);count = 0 ;while(1){//加锁 pthread_mutex_lock(&lock);sleep(1);printf("count:%d\n",count);//解锁 pthread_mutex_unlock(&lock);}return 0 ; }void *thread_func1(void *arg){while(1){pthread_mutex_lock(&lock);//sleep(1);count++ ; pthread_mutex_unlock(&lock);}}void *thread_func2(void *arg){while(1){pthread_mutex_lock(&lock);//sleep(1);count++ ; pthread_mutex_unlock(&lock);}}