2016-09-22 111 views
0

我在線程內創建線程時遇到問題。我需要創建thread1和thread1做「某事」,以及創建thread2,這將做其他事情。如何創建一個在C編程中創建另一個線程的線程?

我的代碼:

#include <pthread.h> 
    #include <stdio.h> 
    #include <errno.h> 
    #include <stdlib.h> 
    #include <unistd.h> 

void *msg1(void *ignored) 
{ 

void *msg2(void *ignored) 
{ 
printf("this is thread2"); 
} 


pthread_t thread; 
int thread2; 
thread2 = pthread_create(&thread, NULL, msg2, NULL); 

return 0; 
} 



int main() 
{ 
pthread_t thread; 
int thread1; 
thread1 = pthread_create(&thread, NULL, msg1, NULL); 
return 1; 


} 

回答

3

創建從一個線程回調內部線程沒有從主線程創建它們的不同。當然,每個線程都需要自己的回調函數 - 這是用給定的pthreads格式聲明的,void* func (void*)

由於未知原因,您嘗試在另一個函數內聲明一個函數。這沒有任何意義,並且不允許使用C線程或不使用線程。

如果你想限制第二個線程的範圍,然後把兩個線程的回調屬於自己的模塊中,並進行第二次回調函數static。這是非常基本的程序設計 - 在推出多線程之前,我建議您先研究一下。

+2

從技術上講,應該有相同行爲的兩個線程當然可以運行相同的線程函數。 – unwind