gpt4 book ai didi

c - 使用互斥锁按顺序同步线程

转载 作者:太空宇宙 更新时间:2023-11-04 02:37:14 24 4
gpt4 key购买 nike

我有这个 C 程序,它必须按 0-6 的顺序显示线程。我正在使用互斥体,但是当我尝试运行我的代码时,没有任何反应,也没有任何显示。另外,编译器没有显示错误

我使用了锁定和解锁互斥体,但我不确定我是否在正确的位置创建了它。任何建议和帮助表示赞赏。

#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 a_mutex = PTHREAD_MUTEX_INITIALIZER;


int main()
{
int i;
pthread_t tid[7];
// Initialize random number generator
time_t seconds;
time(&seconds);
srand((unsigned int) seconds);

int rc;



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

for (i = 0; i < 7; i++)

{ rc = pthread_mutex_lock(&a_mutex);

for (i = 0; i < 7; i++)
{
rc = pthread_mutex_unlock(&a_mutex);
}
}

}
//join threads
for (i=0; i<7; i++)
{
if (pthread_join(tid[i], NULL));
}

rc = pthread_mutex_destroy(&a_mutex);

// Exit main
return 0;

}
void *text(void *arg)
{
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
printf("This is thread %d.\n", n);
// Exit thread
pthread_exit(0);
}

最佳答案

找出问题的关键是问自己这个问题“我的 6 个线程之间共享的数据是什么?” That 是需要在锁定的互斥锁 block 中进行互斥锁保护(读取和写入)的变量。目前,您只是从单个主线程锁定和解锁互斥量,这实际上什么都不做。

你可能想要更接近这个的东西(虽然这可以大大简化 - 例如你可以完全删除 sleep ):

#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 a_mutex = PTHREAD_MUTEX_INITIALIZER;

int main()
{
int i;
pthread_t tid[7];
// 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]);

//join threads
for (i=0; i<7; i++)
if (pthread_join(tid[i], NULL));

pthread_mutex_destroy(&a_mutex);

// Exit main
return 0;
}

void *text(void *arg)
{
long n = (long)arg;
long localNum = -1;
int rand_sec = rand() % (3 - 1 + 1) + 1; // Random num seconds to sleep
int rc;
while ( localNum != n )
{
rc = pthread_mutex_lock(&a_mutex);
localNum = num;
rc = pthread_mutex_unlock(&a_mutex);
sleep(rand_sec); // Sleep for random amount of time
}

printf("This is thread %d.\n", n);

rc = pthread_mutex_lock(&a_mutex);
num++; // Let next thread go
rc = pthread_mutex_unlock(&a_mutex);

pthread_exit(0);
}

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

24 4 0