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 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序