2
任務是讓5個線程同時出現,並且用戶分配每個突發時間。然後使用量程爲2的循環算法來調度線程。舉例來說,如果我有用pthreads模擬循環賽
$ ./m 1 2 3 4 5
運行程序的輸出應該
A 1
B 2
C 2
D 2
E 2
C 1
D 2
E 2
E 1
但現在我的輸出僅顯示
A 1
B 2
C 2
由於程序犯錯其中一個線程不結束暫時,我認爲問題是這個線程不能解鎖讓下一個線程搶鎖。我的睡眠()也不起作用。但我不知道如何修改我的代碼以修復它們。我的代碼如下:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
double times[5];
char process[] = {'A', 'B', 'C', 'D', 'E'};
int turn = 0;
void StartNext(int tid) //choose the next thread to run
{
int i;
for(i = (tid + 1) % 5; times[i] == 0; i = (i + 1) % 5)
if(i == tid) //if every thread has finished
return;
turn = i;
}
void *Run(void *tid) //the thread function
{
int i = (int)tid;
while(times[i] != 0)
{
while(turn != i); //busy waiting till it is its turn
if(times[i] > 2)
{
printf("%c 2\n", process[i]);
sleep(2); //sleep is to simulate the actual running time
times[i] -= 2;
}
else if(times[i] > 0 && times[i] <= 2) //this thread will have finished after this turn
{
printf("%c %lf\n", process[i], times[i]);
sleep(times[i]);
times[i] = 0;
}
StartNext(i); //choose the next thread to run
}
pthread_exit(0);
}
int main(int argc, char **argv)
{
pthread_t threads[5];
int i, status;
if(argc == 6)
{
for(i = 0; i < 5; i++)
times[i] = atof(argv[i + 1]); //input the burst time of each thread
for(i = 0; i < 5; i++)
{
status = pthread_create(&threads[i], NULL, Run, (void *)i); //Create threads
if(status != 0)
{
printf("While creating thread %d, pthread_create returned error code %d\n", i, status);
exit(-1);
}
pthread_join(threads[i], 0); //Join threads
}
}
return 0;
}
該程序可直接運行。任何人都可以幫我弄明白嗎?謝謝!
謝謝。根據你的第一點,我不太瞭解如何修改我的代碼。它仍然不能解決問題......在我的例子中,實際創建了突發時間'4'的線程? – goldfrapp04 2012-03-25 22:53:27
第一點你是對的,你直接將int嵌入指針,我沒有看到。但是那裏可能有問題,是的,在創建線程時,我會回答問題的答案。 – Castilho 2012-03-25 23:05:14
謝謝!我應該已經意識到「加入」問題。現在它是固定的,謝謝:)最後一個問題:什麼是「連接」功能真的在這裏做?如果我刪除這一行,該程序不起作用,但爲什麼? – goldfrapp04 2012-03-25 23:12:19