c - 使用同步线程有什么好处?

标签 c multithreading pthreads thread-synchronization

我对同步线程有疑问。见下面代码

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

相关文章:

java - 使用线程从文件中预取有用吗?

c - 使用指针对数组进行排序 - C 编程

c - 从 uint8_t 类型数组中提取位

c# - StandardOutput 流上已在进行异步读取操作的异常

c++ - 多线程总和

c++ - pthread_mutex_lock.c :62: __pthread_mutex_lock: Assertion `mutex->__data.__owner == 0' failed

Python pthread_detach 模拟

multithreading - 创建一个将一直阻塞直到被n/2个以上线程调用的函数(伪代码)

c - 无法解码一段代码及其用途

c - 排序和打印数组元素打印出垃圾