以特定顺序调整条件线程

时间:2017-11-15 16:03:08

标签: c multithreading pthreads

如何以特定顺序显示主题? 我需要按照以下执行顺序打印条件变量,但我不明白我是如何做到的。

是我需要打印的订单

1 3 1 2 1

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

struct DatoHilo{int dato;};
void * funhilos(void *);
int turno = 0;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t  cond  = PTHREAD_COND_INITIALIZER;

int main(){
    clock_t t_ini, t_fin;
    double secs;
    int nhilos = 0, i=0;
    pthread_t *pidhilos = NULL;
    struct DatoHilo *datohilo;  
    printf("Numero de hilos\n");
    scanf("%d", &nhilos);       
    //creacion de hilos
    pidhilos = (pthread_t *) calloc(nhilos, sizeof(pthread_t));
    for(i=0; i<nhilos; i++){    
        datohilo = (struct DatoHilo*)malloc(sizeof(struct DatoHilo));
        datohilo->dato = i;
        pthread_create(&pidhilos[i], NULL, funhilos, (void*)datohilo);
    }
    t_ini = clock();
    for(i=0; i<nhilos; i++)
        pthread_join(pidhilos[i], NULL);
    t_fin = clock();
    secs = (double)(t_fin - t_ini) / CLOCKS_PER_SEC;
    printf("%.16g milisegundos\n", secs * 1000.0); 

    free(pidhilos);
    return 0;
}

void * funhilos( void *arg){
    int myturno = ((struct DatoHilo *)arg)->dato;

    pthread_mutex_lock(&mutex);
    while(turno != myturno) pthread_cond_wait(&cond, &mutex);
    printf("Hilo turno %d\t[%u]\n", myturno, (unsigned int)pthread_self());
    turno ++;
    pthread_cond_broadcast(&cond);
    pthread_mutex_unlock(&mutex);    
    free(arg);
    pthread_exit(0);
}

1 个答案:

答案 0 :(得分:1)

如果你的订单是1 3 1 2 1 3 ...并且你真的想要使用线程,那么你需要三个条件变量 - 每个线程一个,每次我们将发信号到下一个理想的线程。

这是线程N的基本代码:

pthread_mutex_lock(m);
while(!awakenedN)
    pthread_cond_wait(condN, m);
printf("thread N"); //Nth thread's work
pthread_cond_signal(...); //awaken next thread
awakened... = 1;
awakenedN = 0;
pthread_mutex_unlock(m);

所以你需要的是选择...所代表的内容并且选择非常明显:

int awakened1 = 1, awakened2 = 0, awakened3 = 0;
int turn = 1;

// thread 1
pthread_mutex_lock(m);
while(!awakened1)
    pthread_cond_wait(cond1, m);
printf("thread 1");
// after first thread we can call second or third:
switch(turn) {
    case 1:
        turn = 2;
        awakened3 = 1;
        pthread_cond_signal(cond3);
        break;
    case 2:
        turn = 1;
        awakened2 = 1;
        pthread_cond_signal(cond2);
        break;
}
awakened1 = 0;
pthread_mutex_unlock(m);

// thread 2
pthread_mutex_lock(m);
while(!awakened2)
    pthread_cond_wait(cond2, m);
printf("thread 2");
awakened1 = 1;
awakened2 = 0;
pthread_cond_signal(cond1);
pthread_mutex_unlock(m);

// thread 3
pthread_mutex_lock(m);
while(!awakened3)
    pthread_cond_wait(cond3, m);
printf("thread 3");
awakened1 = 1;
awakened3 = 0;
pthread_cond_signal(cond1);
pthread_mutex_unlock(m);

之后,您可以轻松地对N(线程数)大于3的内容进行概括。