2017-11-15 5 views
0

どのように特定の順序でスレッドを表示できますか? 条件変数を使って次の実行順序を印刷する必要がありますが、どのように実行できるのか分かりません。以下のための1 - ご注文は1 3 1 2 1 3 ...であり、あなたが本当にスレッドを使用する場合、あなたは3つの条件変数が必要な場合は特定の順序のVar条件スレッド

は私が

#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); 
} 
+0

読みやすいように書式設定されたコード – phuzi

答えて

1

を印刷する必要があるためであります各スレッドと次の望ましいスレッドに信号を送ります。

これは、スレッドNための基本的なコードです:あなたができることをした後

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); 

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); 

だから、あなたが必要とするすべてのために...スタンドを行い、選択肢はかなり明白であるものを選択することですN(スレッド数)が3より大きい場合は、これを簡単に一般化してください。