我有这个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);
}