以下是线程的几种同步方式:
1、互斥量。
通过使用pthread的互斥接口保护数据,确保同一时间只有一个线程访问数据。互斥量从本质上讲是一把锁,在访问共享资源前对互斥量进行加锁,在访问完成后释放互斥量上的锁。如下例所示,就是互斥量对共享数据的操作:
#include#includeint value = 5;//共享变量pthread_mutex_t mutex;//互斥变量void *mythread1();void mainshow();int main(){int retval;pthread_t tid1;retval = pthread_create(&tid1,NULL,mythread1,&value);//创建线程if(retval != 0){printf(“Can not create mythread1n”);mainshow();retval = pthread_join(&tid1,NULL);//等待线程mythread1结束if(retval != 0){printf(“Can not join with mythread.n”);printf(“value = %dn”,value);return 0;}void *mythread1(){int retval;retval = pthread_mutex_lock(&mutex);//上锁value = value + 1;//对共享变量的操作printf("value = %dn",value);retval = pthread_mutex_unlock(&mutex);//解锁pthread_exit((void *)0);}void myshow(){int retval;retval = pthread_mutex_lock(&mutex);//上锁value = value + 1;//对共享变量的操作printf(“value = %dn”,value);pthread_mutex_unlock(&mutex);//解锁}
2、信号量
该信号量是Posix提供的基于内存的信号量,它们由应用程序分配信号量的内存空间。如下例所示,就是信号量对共享数据的操作:
#include#include#includeint value = 5;sem_t sem1,sem2;void mainshow();void *mythread();int main(){int retval;pthread_t tid;retval = sem_init(&sem1,0,0);retval = sem_init(&sem2,0,1);retval =pthread_create(&tid,NULL,mythread,NULL);mainshow();pthread_join(tid,NULL);printf("value3 = %dn",value);return 0;}void *mythread(){int retval;retval = sem_wait(&sem1);value = value + 1;printf("value1 = %dn",value);retval = sem_post(&sem2);pthread_exit((void *) 0);}void mainshow(){int retval;retval = sem_wait(&sem2);value = value + 1;printf("value2 = %dn",value);retval = sem_post(&sem1);}