我对同步线程
有疑问。见下面代码
#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
。当两者不同时执行时,线程
有什么用?
有什么线程
可用于同步
的示例吗?
提前致谢。
最佳答案
你的例子不是很明确。我稍微改变了一下:
#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);
printf("send 1000$ to %d\n",a);
sem_post(&s2);
}
}
void* t2handler(void* data)
{
while(1){
sem_wait(&s2);
a++;
printf("client is now #%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;
}
如果线程不同步,则一个客户端可以获得 2000 美元或 0 美元。
在现实世界中,此类线程的可能用途是当一个线程获取输入(例如电影标题)而另一个线程生成输出(流式传输电影)时。
关于c - 使用同步线程有什么好处?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39511437/