函式介紹 :
在這裡使用 API:pthread_create 建立 Thread, 簡單說明如下 :
原型 :
int pthread_create(pthread_t * thread, pthread_attr_t * attr, void *
(*start_routine)(void *), void * arg);
頭文件 : #include
功能 : pthread_create - create a new thread
返回值 :
On success, the identifier of the newly created thread is stored in the location pointed by the thread argument, and a 0 is returned. On error, a non-zero error code is returned.
使用說明 :
pthread_create(3) creates a new thread of control that executes concurrently with the calling thread. The new thread applies the function start_routine passing it arg as first argument. The new thread terminates either explicitly, by calling pthread_exit(3), or implicitly, by returning from the start_routine function. The latter case is equivalent to calling pthread_exit(3) with the result returned by start_routine as exit code.
The attr argument specifies thread attributes to be applied to the new thread. See pthread_attr_init(3) for a complete list of thread attributes. The attr argument can also be NULL, in which case default attributes are used: the created thread is joinable (not detached) and has default (non real-time) scheduling policy.
範例代碼 :
* 在這個範例中會開兩個線程, 並且執行同一個函數, 唯一不同的是不同線程丟進去的參數不同, 實際應用上, 不同線程可以呼叫不同函數.
* 線程的中斷可以直接呼叫 pthread_exit 或者等待線程執行的函數回傳. 如果某線程呼叫函示呼叫 exit(), 則會中斷目前的程序與所有的線程.
- ThreadCreateTest.cpp 代碼 :
#include
#include
#include
void *print_message_function(void *ptr);
int main(){
pthread_t thread1, thread2;
char *message1 = "Thread 1";
char *message2 = "Thread 2";
int iret1, iret2;
/*Create independ threads each of which will execute function*/
iret1 = pthread_create(&thread1, NULL, print_message_function, (void*) message1);
iret2 = pthread_create(&thread2, NULL, print_message_function, (void*) message2);
/*Wait till threads are complete before main continues. Unless we wait and we run the risk of executing an exit*/
/*which will terminate the process and all threads before the thread have completed. */
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
printf("Thread1 returns: %d\n", iret1);
printf("Thread2 returns: %d\n", iret2);
return 0;
}
void *print_message_function(void *ptr) {
char *message;
message = (char*) ptr;
printf("%s\n", message);
}
執行結果 :
linux-tl0r:~/gccprac/Test # g++ -o ThreadCreateTest -lpthread ThreadCreateTest.cpp <編譯程式>
ThreadCreateTest.cpp: In function ‘int main()’:
ThreadCreateTest.cpp:9: warning: deprecated conversion from string constant to ‘char*’
ThreadCreateTest.cpp:10: warning: deprecated conversion from string constant to ‘char*’
linux-tl0r:~/gccprac/Test # ./ThreadCreateTest <執行程式>
Thread 2
Thread 1
Thread1 returns: 0
Thread2 returns: 0
沒有留言:
張貼留言