我有這個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);
}