- 論壇徽章:
- 0
|
- #include <stdio.h>
- #include <stdlib.h>
- #include <pthread.h>
- void *thrd_func(void *arg);
- pthread_t tid;
- int main(){
- // 創(chuàng)建線程tid,且線程函數(shù)由thrd_func指向,是thrd_func的入口點,即馬上執(zhí)行此線程函數(shù)
- if (pthread_create(&tid,NULL,thrd_func,NULL)!=0) {
- printf("Create thread error!\n");
- exit(1);
- }
- printf("TID in pthread_create function: %u.\n",tid);
- printf("Main process: PID: %d,TID: %u.\n",getpid(),pthread_self());
-
- sleep(1); //race
- return 0;
- }
- void *thrd_func(void *arg){
- // printf("I am new thread!\n");
- printf("New process: PID: %d,TID: %u.\n",getpid(),pthread_self()); //why pthread_self
- printf("New process: PID: %d,TID: %u.\n",getpid(),tid); //why pthread_self
- pthread_exit(NULL); //退出線程
- // return ((void *)0);
- }
復(fù)制代碼 程序運(yùn)行結(jié)果是:
2013-11-15_155916.jpg (12.62 KB, 下載次數(shù): 31)
下載附件
2013-11-15 15:59 上傳
剛剛接觸linux的線程編程,所以有很多不懂的地方,這是某位大牛博客上的一段程序。
1. 我不理解的是,在函數(shù)void thrd_func(void *)中,并沒有定義tid這個變量,而使用了printf輸出,這樣不會造成內(nèi)存引用錯誤嗎?
2. 還有一點不理解的地方是, 為什么在main函數(shù)中pthread_self()返回值是3079558848,而在void thrd_func( )函數(shù)中thread_sel()返回值是3079555952.
希望大家可以解答一下。 |
|