第一次使用pthread,遇到的問題還真不少,現在我一一記錄一下:
1.關於編譯時出現 對『pthread_create』未定義的引用 之類的錯誤的解決:由於pthread庫不是linux系統預設的庫,連線時需要使用庫libpthread.a,所以在使用pthread_create建立執行緒時,在編譯中要加-lpthread引數:
gcc -o pthread -lpthread pthread.c
特別的,如果這樣還沒解決的話:
按照上面編譯了一下,還是一樣的提示.
後面man gcc
才知道usage: gcc [options] file...
因此需要將庫鏈結放在末尾。
xs@vm:~/desktop$ gcc -o pthread pthread.c -lpthread
2.關於pthread裡的一些函式.
pthread_join函式:
函式pthread_join用來等待乙個執行緒的結束。
函式定義:int pthread_join(pthread_t thread, void **retval);
描述 :
pthread_join()函式,以阻塞的方式等待thread指定的執行緒結束。當函式返回時,被等待執行緒的資源被收回。如果程序已經結束,那麼該函式會立即返回。並且thread指定的執行緒必須是joinable的。
引數 :
thread: 執行緒識別符號,即執行緒id,標識唯一執行緒。
retval: 使用者定義的指標,用來儲存被等待執行緒的返回值。
返回值 : 0代表成功。 失敗,返回的則是錯誤號。
看下面一段程式:
[cpp]view plain
copy
print?
#include
#include
#include
void
*thread
(void
*str)
return
null;
} int
main()
return
0;
}
如果我們注釋掉"pthread_join(pth, null);"這一行:
執行結果如下:
也就是說:子執行緒還沒有執行完畢,main函式已經退出,那麼子執行緒也就退出了!
如果我們不注釋掉那一行,那麼執行結果如下:
這說明:pthread_join函式的呼叫者在等待子執行緒退出後才繼續執行!
pthread_create函式:
宣告:
int pthread_create(pthread_t *thread,
const pthread_attr_t *restrict_attr,
void*(*start_rtn)(void*),
void *restrict arg);
引數:
第乙個引數*thread為指向執行緒識別符號的指標。
第二個引數*restrict_attr用來設定執行緒屬性,上面也可以用null,表示使用預設的屬性。
第三個引數是執行緒執行函式的起始位址。
最後乙個引數是執行函式的引數,null表示無引數。
另外,在編譯時注意加上-lpthread引數,以呼叫鏈結庫。因為pthread並非linux系統的預設庫,而是posix執行緒庫,在linux中將其作為乙個庫來使用,因此加上 -lpthread(或-pthread)以顯示的鏈結該庫。函式在執行錯誤時的錯誤資訊將作為返回值返回,並不修改系統全域性變數errno,當然也無法使用perror()列印錯誤資訊。
pthread_t:pthread_t用於宣告執行緒id!
型別定義:
typedef unsigned long int pthread_t;
//come from /usr/include/bits/pthread.h
sizeof (pthread_t) =4;
pthread_attr_init函式:
宣告:int pthread_attr_init(pthread_attr_t*attr);
返回值:返回0,表示函式初始化物件成功。失敗時返回乙個錯誤**。
引數:指向乙個執行緒屬性的指標。
下面乙個程式是書上的:
[cpp]view plain
copy
print?
/*小小的乙個程式,折騰人個半死*/
#include
#include
#include
intsum;
void
*runner (
void
*param);
intmain(
intargc,
char
*argv)
if(atoi(argv[1] )
pthread_attr_init(&attr); /*初始化,得到預設的屬性值*/
pthread_create(&tid, &attr, runner, argv[1]);/*建立乙個執行緒*/
pthread_join(tid, null);/*等待子執行緒執行完畢*/
printf ("sum = %d\n"
, sum);
return
0;
} void
*runner(
void
*param)
/*子執行緒將會執行這個函式*/
pthread_exit(0);
}
關於pthread裡面一些函式的使用心得!
第一次使用pthread,遇到的問題還真不少,現在我一一記錄一下 1.關於編譯時出現 對 pthread create 未定義的引用 之類的錯誤的解決 由於pthread庫不是linux系統預設的庫,連線時需要使用庫libpthread.a,所以在使用pthread create建立執行緒時,在編譯...
關於pthread裡面一些函式的使用心得!
第一次使用pthread,遇到的問題還真不少,現在我一一記錄一下 1.關於編譯時出現 對 pthread create 未定義的引用 之類的錯誤的解決 由於pthread庫不是linux系統預設的庫,連線時需要使用庫libpthread.a,所以在使用pthread create建立執行緒時,在編譯...
虛函式的一些總結
虛函式與虛函式表 1 每個類只有乙個虛函式表 如 cout int int bb1 其中對於 cout int int bb1 bb1是取得物件的首位址,因為含有虛函式的物件中的首位址儲存的是虛指標的位址,所以 bb1就是虛指標的位址 int bb1是將虛函式的位址解釋為int型別 int bb1 ...