gpt4 book ai didi

c - Var 条件线程按特定顺序排列

转载 作者:行者123 更新时间:2023-11-30 14:53:13 26 4
gpt4 key购买 nike

如何按特定顺序显示线程?我需要使用条件变量打印以下执行顺序,但我不明白如何做到这一点。

这是我需要打印的订单

13121

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

之后,您可以轻松地将其推广到大于 3 的 N(线程数)。

关于c - Var 条件线程按特定顺序排列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47312043/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com