我試圖運行下面的代碼。在這個question的幫助下,我能夠理解應該創建多少個進程和線程,但是,爲了讓這個更進一步,我嘗試讓線程執行一個函數。執行線程 - 輸出原因
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
void *runner(void *param) {
int i = atoi(param);
printf("My thread id is %ld\n",pthread_self());
printf("\nValue of parameter = %d", i);
pthread_exit(0);
}
int main()
{
int i = 5;
pid_t pid;
pthread_t tid;
pthread_attr_t attr;
pid = fork(); wait(NULL);
if (pid == 0) { /* Child Process */
fork(); wait(NULL);
pthread_attr_init(&attr);
i++;
pthread_create(&tid, &attr, runner, &i);
pthread_join(tid, NULL);
}
fork(); wait(NULL);
printf("\n\n");
return 0;
}
這種情況的輸出是: 我的線程id是139919964464896
Value參數= 0
Value參數= 0
我的線程id是139919964464896
參數值= 0
Value參數= 0
這裏,我無法弄清楚:
- 爲什麼行我的線程ID爲139919964464896得到,而線值參數= 0獲取打印打印兩次四次。
- 爲什麼當傳遞的參數初始化爲5並增加到6時,該值會打印爲0?
請問,有人可以幫助我嗎?提前致謝!
我剛開始閱讀操作系統,這是很多有用的信息。非常感謝解釋! :) – Neha
不客氣! –