1.linux上線程開發api概要
多執行緒開發在 linux 平台上已經有成熟的 pthread 庫支援,(在程式執行的時候要假如-lpthread),其涉及的多執行緒開發的最基本概念主要包含三點:執行緒,互斥鎖,條件。其中,執行緒操作又分執行緒的建立,退出,等待 3 種。互斥鎖則包括 4 種操作,分別是建立,銷毀,加鎖和解鎖。條件操作有 5 種操作:建立,銷毀,觸發,廣播和等待。
2.執行緒的建立,退出以及等待
(1)執行緒的建立原型
第乙個引數pthread_t :為長整形的指標#include
intpthread_create
(pthread_t *restrict tidp,
const pthread_attr_t *restrict attr,
void*(
*start_rtn)
(void*)
,void
*restrict arg)
;
第二個引數const pthread_attr_t:為執行緒的屬性
第三個引數void *(*start_rtn)(void *):呼叫相關的函式
第四個引數 void *restrict arg:給執行緒傳參的引數
當pthread_create成功返回時,由tidp指向的記憶體單元被設定為新建立執行緒的執行緒id。attr引數用於定製各種不同的執行緒屬性,暫可以把它設定為null,以建立預設屬性的執行緒。
新建立的執行緒從start_rtn函式的位址開始執行,該函式只有乙個無型別指標引數arg。如果需要向start_rtn函式傳遞的引數不止乙個,那麼需要把這些引數放到乙個結構中,然後把這個結構的位址作為arg引數傳入。
(2)執行緒退出原型
(3)執行緒等待原型#include
intpthread_exit
(void
*rval_ptr)
;
// 返回:若成功返回0,否則返回錯誤編號#include
intpthread_join
(pthread_t thread,
void
**rval_ptr)
;
——@ 峰子_仰望陽光
3.實現執行緒的退出,建立及等待
(1)執行緒的建立:
(2)執行緒等待pthread_join#include
#include
//int pthread_create(pthread_t *restrict tidp, const pthread_attr_t *restrict attr, void *(*start_rtn)(void *), void *restrict arg);
void
*func1
(void
*arg)
//變數名
intmain()
printf
("main:%ld \n",(
unsigned
long
)pthread_self()
);while(1
);//不讓主線程退出,接著列印新的執行緒
return0;
}
執行結果:#include
#include
//int pthread_create(pthread_t *restrict tidp, const pthread_attr_t *restrict attr, void *(*start_rtn)(void *), void *restrict arg);
void
*func1
(void
*arg)
intmain()
printf
("main:%ld \n",(
unsigned
long
)pthread_self()
);pthread_join
(t1,
null);
return0;
}
執行結果一樣,讓t1執行後,主線程退出。
作用:呼叫這個函式的執行緒將一直阻塞,直到指定的執行緒呼叫pthread_exit會退出,也就是說pthread_join也可以**執行緒退出的狀態。
3.**執行緒退出的狀態
(1)返回乙個整數
執行結果:#include
#include
//int pthread_create(pthread_t *restrict tidp, const pthread_attr_t *restrict attr, void *(*start_rtn)(void *), void *restrict arg);
void
*func1
(void
*arg)
intmain()
printf
("main:%ld \n",(
unsigned
long
)pthread_self()
);pthread_join
(t1,
(void**
)&pret)
;printf
("main: t1 quit:%d\n"
,*pret)
;return0;
}
(2)返回乙個字串
在定義引數的時候要加入static,否則返回值會跑飛掉。#include
#include
//int pthread_create(pthread_t *restrict tidp, const pthread_attr_t *restrict attr, void *(*start_rtn)(void *), void *restrict arg);
void
*func1
(void
*arg)
intmain()
printf
("main:%ld \n",(
unsigned
long
)pthread_self()
);pthread_join
(t1,
(void**
)&pret)
;printf
("main: t1 quit:%s\n"
,pret)
;return0;
}
——@上官可程式設計
Linux系統程式設計 執行緒建立等待及退出2
實現如下 執行緒同步之互斥量加鎖解鎖和互斥鎖限制共享資源的訪問 案例 include include int g data 0 pthread mutex t mutex void func1 void arg void func2 void arg int main ret2 pthread cr...
程序的建立,等待,退出,
標頭檔案 include 定義函式 int system const char string 函式說明 system 會呼叫fork 產生子程序,由子程序來呼叫 bin sh c string來執行引數string字串所代表的命令,此命令執行完後隨即返回原呼叫的程序。在呼叫system 期間sigc...
建立程序並等待程序退出
cereatepross.cpp 定義控制台應用程式的入口點。include stdafx.h include include include include include using namespace std bool findandkillprocessbyname lpctstr strp...