线程的两种同步方式测试

来源:互联网 发布:Linux netstat -i 编辑:程序博客网 时间:2024/04/23 18:49

创建线程:

#include<pthread.h>#include<stdio.h>#include<unistd.h>void *foo(void *arg){printf("%s", (char*)arg);getchar();pthread_exit("!!!!!!!!!\n");}int main(){pthread_t pt;void *result="aaa";char arg[] = "~~~~~~";pthread_create(&pt, NULL, foo, arg);sleep(5);pthread_join(pt, &result);printf("result:%s\n", (char*)result);return 0;}


信号量同步:

#include<semaphore.h>#include<pthread.h>#include<stdio.h>#include<string.h>sem_t sem;sem_t semw;char buf[20];void *foo(void *t){while(1){sem_wait(&sem);sleep(3);printf("--------------%s\n", buf);sem_post(&semw);}pthread_exit("");}int main(){pthread_t thread;sem_init(&sem, 0, 0);sem_init(&semw, 0, 1);pthread_create(&thread, NULL,foo, "");do{sem_wait(&semw);gets(buf);sem_post(&sem);}while(strcmp(buf,"exit")!= 0);return 0;}

互斥锁同步:

#include<pthread.h>#include<stdio.h>#include<stdlib.h>#define _LOCK_int value1, value2;pthread_mutex_t mutex;unsigned int count = 0;void *foo(void *t){while(1){#ifdef _LOCK_pthread_mutex_lock(&mutex);#endifif(value1 != value2){printf("coutn=%d, value1=%d, value2=%d\n",count, value1,value2);}#ifdef _LOCK_pthread_mutex_unlock(&mutex);#endif}}int main(){pthread_t pth;if(pthread_create(&pth, NULL, foo, NULL)<0){perror("");exit(-1);}while(1){count++;#ifdef _LOCK_pthread_mutex_lock(&mutex);#endifvalue1 = count;value2 = count;#ifdef _LOCK_pthread_mutex_unlock(&mutex);#endif}return 0;}


原创粉丝点击