0
我对synchronized threads
有疑问。请参见下面的代码使用同步线程的优点是什么?
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<pthread.h>
#include<sys/types.h>
#include<semaphore.h>
int a=0;
sem_t s1, s2;
void* t1handler(void *data)
{
while(1){
sem_wait(&s1);
a++;
printf("incr %d\n",a);
sem_post(&s2);
}
}
void* t2handler(void* data)
{
while(1){
sem_wait(&s2);
a--;
printf("decr %d\n",a);
sem_post(&s1);
}
}
int main(){
pthread_t t1,t2;
sem_init(&s1,0,1);
sem_init(&s2,0,0);
pthread_create(&t1,NULL,t1handler,NULL);
pthread_create(&t2,NULL,t2handler,NULL);
pthread_join(t1,NULL);
pthread_join(t2,NULL);
return 0;
}
可能不是一个很好的例子,但在这里thread2
等待thread1
完成,反之亦然synchronize
。当两者不同时执行时,threads
的用法是什么?
其中threads
可用于synchronization
的任何示例?
在此先感谢。
Errr ...你写的代码,你告诉我们*它的重点是什么。 –
@KerrekSB这只是一个例子。问题是我可以在哪里使用同步线程 –
用你的简单例子:如果线程1执行增加('a ++'),那么线程被抢占并且线程2减少,那么线程2被抢占并且线程1继续, “a”的价值不是它的价值。使用“同步”时,在任何一个线程中'a'的值都不会意外变化。 –