2016-09-15 26 views
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的任何示例?

在此先感谢。

+1

Errr ...你写的代码,你告诉我们*它的重点是什么。 –

+0

@KerrekSB这只是一个例子。问题是我可以在哪里使用同步线程 –

+1

用你的简单例子:如果线程1执行增加('a ++'),那么线程被抢占并且线程2减少,那么线程2被抢占并且线程1继续, “a”的价值不是它的价值。使用“同步”时,在任何一个线程中'a'的值都不会意外变化。 –

回答

1

你的例子不是很明确。我稍微改变了它:

#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。

在现实世界中,这样的线程的可能用途是当一个人获得输入(例如电影标题)并且另一个人正在产生输出(流式传输电影)时。