gpt4 book ai didi

C - 使用互斥锁同步多个线程

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

我正在尝试同步多个 (7) 线程。我以为我理解它们是如何工作的,直到我在我的代码上尝试它并且我的线程仍然乱序打印。这是代码:

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
#include <time.h>
void *text(void *arg);
long code[] = {4,6,3,1,5,0,2}; //Order in which to start threads
int num = 0;
pthread_mutex_t lock; //Mutex variable

int main()
{
int i;
pthread_t tid[7];

//Check if mutex worked
if (pthread_mutex_init(&lock, NULL) != 0){
printf("Mutex init failed\n");
return 1;
}

//Initialize random number generator
time_t seconds;
time(&seconds);
srand((unsigned int) seconds);

//Create our threads
for (i=0; i<7; i++)
pthread_create(&tid[i], NULL, text, (void*)code[i]);

//Wait for threads to finish
for (i=0; i<7; i++){
if(pthread_join(tid[i], NULL)){
printf("A thread failed to join\n");
}
}
//Destroy mutex
pthread_mutex_destroy(&lock);

//Exit main
return 0;
}

void *text (void *arg)
{
//pthread_mutex_lock(&lock); //lock

long n = (long) arg;
int rand_sec = rand() % (3 - 1 + 1) + 1; //Random num seconds to sleep
while (num != n) {} //Busy wait used to wait for our turn
num++; //Let next thread go
sleep(rand_sec); //Sleep for random amount of time

pthread_mutex_lock(&lock); //lock
printf("This is thread %d.\n", n);

pthread_mutex_unlock(&lock); //unlock
//Exit thread
pthread_exit(0);
}

所以在这里我试图让线程 0-6 按顺序打印,但现在它们仍然是困惑的。注释掉的互斥锁是我最初拥有它的位置,但后来将其移至 print 语句上方的行,但我得到了类似的结果。我不确定我的互斥体中的错误在哪里,有人可以给出提示或指出我正确的方向吗?对此,我真的非常感激。提前致谢!

最佳答案

仅使用互斥锁无法使线程按顺序运行,因为它们以不可预测的顺序执行。在我的方法中,我使用条件变量和共享整数变量来创建排队系统。每个线程都有一个编号,当current_n编号等于实际线程的编号时,它进入临界区并打印其编号。

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

#define N_THREAD 7

int current_n = 0;

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t number = PTHREAD_COND_INITIALIZER;


void *text (void *arg) {
int i = (int)arg;

pthread_mutex_lock(&mutex);
while ( i > current_n ) {
pthread_cond_wait(&number, &mutex);
}

//i = current_n at this point

/*I use stderr because is not buffered and the output will be printed immediately.
Alternatively you can use printf and then fflush(stdout).
*/
fprintf(stderr, "I'm thread n=%d\n", i);
current_n ++;

pthread_cond_broadcast(&number);
pthread_mutex_unlock(&mutex);
return (void*)0;
}

int main() {
pthread_t tid[N_THREAD];

int i = 0;
for(i = 0; i < N_THREAD; i++) {
pthread_create(&tid[i], NULL, text, (void *)i);
}

for(i = 0; i < N_THREAD; i++) {
if(pthread_join(tid[i], NULL)) {
fprintf(stderr, "A thread failed to join\n");
}
}

return 0;
}

输出为:

I'm thread n=0
I'm thread n=1
I'm thread n=2
I'm thread n=3
I'm thread n=4
I'm thread n=5
I'm thread n=6

编译为gcc -Wall -Wextra -O2 test.c -o test -lpthread

不用担心警告。

关于C - 使用互斥锁同步多个线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35807946/

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