C++?pthread入門指南
一、pthread簡介
pthread是C++98接口且只支持Linux,使用時需要包含頭文件#include <pthread.h>,編譯時需要鏈接pthread庫,其中p是POSIX的縮寫,而POSIX是Portable Operating System Interface的縮寫,是IEEE為要在各種UNIX操作系統(tǒng)上運行軟件,而定義API的一系列互相關聯(lián)的標準的總稱。(Windows環(huán)境下無pthread,Linux GCC4.6以下編譯需加-pthread編譯選項)
1、線程創(chuàng)建
int pthread_create (pthread_t *thread, pthread_attr_t *attr, void *(*start_routine)(void *),void *arg);
若創(chuàng)建成功,返回0;若出錯,則返回錯誤編號。
- thread 是線程標識符,但這個參數不是由用戶指定的,而是由 pthread_create 函數在創(chuàng)建時將新的線程的標識符放到這個變量中。
- attr 指定線程的屬性,包含了線程的調度策略,堆棧的相關信息,join or detach 的狀態(tài)等,可以用 NULL 表示默認屬性。
- start_routine 指定線程開始運行的函數。
- arg 是 start_routine 所需要的參數,是一個無類型指針。
pthread_attr_t 操作函數:
pthread_attr_t attr; // 聲明attr pthread_attr_init(&attr); // 創(chuàng)建attr pthread_attr_destroy(&attr); // 銷毀attr pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); // 設置為joinable
2、線程終止
void pthread_exit (void *retval); int pthread_cancel (pthread_t thread);
當發(fā)生以下情形之一時,線程就會結束:
- 線程運行的函數return了,也就是線程的任務已經完成;
- 線程調用了 pthread_exit 函數;
- 其他線程調用 pthread_cancel 結束這個線程;
- 進程調用 exec() 或 exit(),結束了;
- main() 函數先結束了,而且 main() 自己沒有調用 pthread_exit 來等所有線程完成任務。
當然,一個線程結束,并不意味著它的所有信息都已經消失,后面會看到僵尸線程的問題。
一個線程可以通過調用 pthread_cancel 函數來請求取消同一進程中的線程,這個線程由thread 參數指定。如果操作成功則返回0,失敗則返回對應的錯誤編號。
3、線程同步
int pthread_join(pthread_t threadid, void **value_ptr); int pthread_detach (threadid);
阻塞是線程之間同步的一種方法。pthread_join 函數會讓調用它的線程等待 threadid 線程運行結束之后再運行,value_ptr 存放了其他線程的返回值。
一個可以被join的線程,僅僅可以被別的一個線程 join,如果同時有多個線程嘗試 join 同一個線程時,最終結果是未知的。另外,線程不能 join 自己。
值得注意的的是:僵尸線程 ( “zombie” thread )是一種已經退出了的 joinable 的線程,但是等待其他線程調用
pthread_join 來 join 它,以收集它的退出信息(exit status)。如果沒有其他線程調用 pthread_join 來
join 它的話,它占用的一些系統(tǒng)資源不會被釋放,比如堆棧。如果main()函數需要長時間運行,并且創(chuàng)建大量 joinable的線程,就有可能出現堆棧不足的 error 。 對于那些不需要 join 的線程,最好利用
pthread_detach,這樣它運行結束后,資源就會及時得到釋放。注意一個線程被使用 pthread_detach
之后,它就不能再被改成 joinable 的了。 總而言之,創(chuàng)建的每一個線程都應該使用 pthread_join 或者
pthread_detach 其中一個,以防止僵尸線程的出現。
4、其他函數
pthread_self (); // 返回當前線程的 thread ID pthread_equal (thread1,thread2); // pthread_equal 比較兩個線程的 ID,如果不同則返回0,否則返回一個非零值 // 互斥鎖 pthread_mutex_t mutexsum; pthread_mutex_init (mutex,attr); pthread_mutex_destroy (pthread_mutex_t *mutex); pthread_mutexattr_init (attr); pthread_mutexattr_destroy (attr); phtread_mutex_lock(pthread_mutex_t *mutex); phtread_mutex_trylock(pthread_mutex_t *mutex); phtread_mutex_unlock(pthread_mutex_t *mutex);
5、示例代碼
#include<stdlib.h>
#include <pthread.h>
#include <stdio.h>
#include <math.h>
#define NUM_THREADS 4
void *BusyWork(void *t)
{
int i;
long tid;
double result = 0.0;
tid = (long) t;
printf("Thread %ld starting...\n", tid);
for (i = 0; i < 1000000; i++)
{
result = result + sin(i) * tan(i);
}
printf("Thread %ld done. Result = %e\n", tid, result);
pthread_exit((void *) t);
}
int main(int argc, char *argv[])
{
pthread_t thread[NUM_THREADS];
pthread_attr_t attr;
int rc;
long t;
void *status;
/* Initialize and set thread detached attribute */
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
for (t = 0; t < NUM_THREADS; t++)
{
printf("Main: creating thread %ld\n", t);
rc = pthread_create(&thread[t], &attr, BusyWork, (void *) t);
if (rc)
{
printf("ERROR; return code from pthread_create() is %d\n", rc);
exit(-1);
}
}
/* Free attribute and wait for the other threads */
pthread_attr_destroy(&attr);
for (t = 0; t < NUM_THREADS; t++)
{
rc = pthread_join(thread[t], &status);
if (rc)
{
printf("ERROR; return code from pthread_join() is %d\n", rc);
exit(-1);
}
printf("Main: completed join with thread %ld having a status of %ld\n", t, (long) status);
}
printf("Main: program completed. Exiting.\n");
pthread_exit(NULL);
}Main: creating thread 0 Main: creating thread 1 Thread 0 starting... Thread 1 starting... Main: creating thread 2 Main: creating thread 3 Thread 2 starting... Thread 3 starting... Thread 1 done. Result = -3.153838e+06 Thread 0 done. Result = -3.153838e+06 Main: completed join with thread 0 having a status of 0 Main: completed join with thread 1 having a status of 1 Thread 3 done. Result = -3.153838e+06 Thread 2 done. Result = -3.153838e+06 Main: completed join with thread 2 having a status of 2 Main: completed join with thread 3 having a status of 3 Main: program completed. Exiting.
參考鏈接:C++ 多線程編程(二):pthread的基本使用
到此這篇關于C++ pthread入門指南的文章就介紹到這了,更多相關C++ pthread內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

