以下程序的問題是主線程在其他線程有機會顯示其結果之前結束。另一個問題是線程顯示不正確。線程編程問題
的輸出要求是:
This is thread 0.
This is thread 1.
This is thread 2. etc.
代碼:
#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;
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]);
// 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);
}
任何人都可以使用互斥來解決同步問題幫助嗎?
你的序列化要求就像是要求你的新車裝上方形的車輪,而且無論如何,互斥對於這種情況來說都是不恰當的機制。 –
您可以使用障礙來同步修復線程查殺問題的所有線程。此外,還沒有任何已知的線程順序對齊方法。它首先殺死了線程的目的。您需要明確使用共享內存來發出線程串行打印序列的信號。 – jada12276
基本上,通過應用互斥鎖和同步,您正在消除您可能具有的多線程優勢。通常它會比其對應的單線程應用程序慢。關於在任何線程完成之前退出應用程序的第二個問題,可以使用join在退出之前等待所有線程完成。 – Saleem