pfgmylove 2017-02-23 11:59 采纳率: 0%
浏览 3585
已结题

pthread_cond_signal用法问题

请看下述代码是否有问题
疑问点:是否可以主线程触发->A->B->C->A(->表示pthread_cond_signal)

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include <string.h>

using namespace std;

pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond1 = PTHREAD_COND_INITIALIZER;

pthread_mutex_t mutex2 = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond2 = PTHREAD_COND_INITIALIZER;

pthread_mutex_t mutex3 = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond3 = PTHREAD_COND_INITIALIZER;
int count = 10;
int thd_id = 0;

void * thread_func1(void * arg)
{
    for(int i = 0; i < count; i++)
    {
        pthread_mutex_lock(&mutex1);
        pthread_cond_wait(&cond1, &mutex1);
        printf("A");
        pthread_mutex_unlock(&mutex1);

        // notify B
        pthread_cond_signal(&cond2);
    }
    return (void*)0;
}

void * thread_func2(void * arg)
{
    for(int i = 0; i < count; i++)
    {
        pthread_mutex_lock(&mutex2);
        pthread_cond_wait(&cond2, &mutex2);
        printf("B");
        pthread_mutex_unlock(&mutex2);

        // notify C
        pthread_cond_signal(&cond3);
    }
    return (void*)0;
}

void * thread_func3(void * arg)
{
    for(int i = 0; i < count; i++)
    {
        pthread_mutex_lock(&mutex3);
        pthread_cond_wait(&cond3, &mutex3);
        printf("C");
        pthread_mutex_unlock(&mutex3);

        // notify A
        pthread_cond_signal(&cond1);
    }
    return (void*)0;
}

int main()
{
    pthread_t thd1, thd2, thd3;
    if(pthread_create(&thd1, NULL, thread_func1, NULL) != 0)
    {
        printf("Create thread failed.\n");
    }

    if(pthread_create(&thd2, NULL, thread_func2, NULL) != 0)
    {
        printf("Create thread failed.\n");
    }

    if(pthread_create(&thd3, NULL, thread_func3, NULL) != 0)
    {
        printf("Create thread failed.\n");
    }
    // first notify A
    pthread_cond_signal(&cond1);

    void *ret;
    pthread_join(thd1, &ret);
    pthread_join(thd2, &ret);
    pthread_join(thd3, &ret);

    return 0;
}

  • 写回答

1条回答 默认 最新

  • devmiao 2017-02-23 18:42
    关注
    评论

报告相同问题?

悬赏问题

  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)