gpt4 book ai didi

c - 我怎样才能按这个顺序执行3个线程呢?

转载 作者:行者123 更新时间:2023-11-30 19:32:08 27 4
gpt4 key购买 nike

我遇到了问题。我已经尝试了几天在 C 中按以下顺序执行 3 个线程:线程1线程3线程1线程2主题 1

我使用条件变量。这是我的代码,只需打印:

主题 1主题 3

并且它仍然被阻止

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

struct node{
int val;
};

void * function(void *);
int turn = 1,var = 3;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;


int main(){

int i;
pthread_t *pidthreads = NULL;

struct node *data;


pidthreads = (pthread_t *) calloc(3, sizeof(pthread_t));
pthread_mutex_lock(&mutex);
for(i=1; i<=3; i++){
data = (struct node*)malloc(sizeof(struct node));
data->val = i;
pthread_create(&pidthreads[i], NULL, function, (void*)data);
printf("Thread [%u] has been created\n", (unsigned int)pidthreads[i]);
}
pthread_mutex_unlock(&mutex);

for(i=1; i<=3; i++)
pthread_join(pidthreads[i], NULL);

return 0;
}

void * function( void *arg){
int myturn = ((struct node *)arg)->val;

pthread_mutex_lock(&mutex);
while(turn != myturn) pthread_cond_wait(&cond, &mutex);

printf("Thread %d\t[%u]\n", myturn, (unsigned int)pthread_self());

if(turn == 1){
turn=var;
var--;
}else{
if(turn == 3){
turn = 1;
}else{
if(turn == 2){
turn = 1;
}
}
}

pthread_cond_broadcast(&cond);
pthread_mutex_unlock(&mutex);

}

我真的不知道该怎么做。我感谢任何帮助。

最佳答案

像这样在函数中添加一个循环。

int myturn = ((struct node *)arg)->val;

while(true){ // add loop

pthread_mutex_lock(&mutex);
while(turn != myturn) pthread_cond_wait(&cond, &mutex);
....
pthread_cond_broadcast(&cond);
pthread_mutex_unlock(&mutex);
}

但是你必须加上离开的条件。

while(true){

pthread_mutex_lock(&mutex);
// conditions to leave the waitting loop
while(turn != myturn && turn!=0) pthread_cond_wait(&cond, &mutex);

if(turn==0) { // conditions to leave the infinite loop
pthread_mutex_unlock(&mutex);
break;
}
printf("Thread %d\t[%u]\n", myturn, (unsigned int)pthread_self());
...
pthread_mutex_unlock(&mutex);
}

关于c - 我怎样才能按这个顺序执行3个线程呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47383372/

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