一、linux 下相關函式
函式描述
intpthread_create
(pthread_t *thread, pthread_attr_t * attr, void* (*start_routine)(void *),void *arg);
建立乙個新的執行緒。編譯時帶上-lpthread
.
引數說明:
thread: 是乙個指標,執行緒建立成功時,用以返回建立的執行緒id
attr:指定執行緒屬性,null表示使用預設屬性
start_routine:函式指標,指向執行緒建立後要呼叫的函式。這個被執行緒呼叫的函式也稱為執行緒函式
arg:該引數指向傳遞給執行緒函式的引數
extern intpthread_join
__p (pthread_t __th, void **__thread_return);
用來等待乙個執行緒的結束。
引數說明:
__th:被等待的執行緒識別符號
__thread_return:乙個使用者定義的指標,它可以用來儲存被等待執行緒的返回值。
extern voidpthread_exit
__p ((void *__retval))attribute((noreturn));
終止指定執行緒。
引數說明:
__retval:函式的返回**,只要pthread_join中的第二個引數
thread_return不是null,這個值將被傳遞給 thread_return
int
pthread_create
(pthread_t thread, pthread_attr_t * attr,
void
(*start_routine)
(void*)
,void
*arg)
;extern
int pthread_join __p (pthread_t __th,
void
**__thread_return)
;extern
void pthread_exit __p (
(void
*__retval)
) attribute (
(noreturn)
);
二、鎖
2.1 互斥鎖
extern
int pthread_mutex_init (pthread_mutex_t *__mutex,
const pthread_mutexattr_t *__mutexattr)
__throw __nonnull ((1
));
函式2.1 pthread_mutex_lock 與 pthread_mutex_unlockpthread_mutex_init
用來生成乙個互斥鎖。null引數表明使用預設屬性。如果需要宣告特定屬性的互斥鎖,須呼叫函式 pthread_mutexattr_init.
函式
pthread_mutexattr_setpshared
和函式pthread_mutexattr_settype
用來設定互斥鎖屬性。前乙個函式設定屬性
pshared
,它有兩個取值,pthread_process_private
和pthread_process_shared
.前者用來對不同程序中的執行緒同步,後者用於同步本程序的不同執行緒。後者用來設定互斥鎖型別,可選的型別有
pthread_mutex_normal
、pthread_mutex_errorcheck
、pthread_mutex_recursive
和pthread _mutex_default
.它們分別定義了不同的上所、解鎖機制,一般情況下,選用最後乙個預設屬性。
extern
int pthread_mutex_lock (pthread_mutex_t *__mutex)
__thrownl __nonnull ((1
));
extern
int pthread_mutex_unlock (pthread_mutex_t *__mutex)
__thrownl __nonnull ((1
));
pthread_mutex_lock
宣告開始用互斥鎖上鎖,此後的**直至呼叫pthread_mutex_unlock
為止,均被上鎖,即同一時間只能被乙個執行緒呼叫執行。當乙個執行緒執行到pthread_mutex_lock
處時,如果該鎖此時被另乙個執行緒使用,那此執行緒被阻塞,即程式將等待到另乙個執行緒釋放此互斥鎖。
三、執行緒休眠
3.1 sleep 與 usleep
extern
unsigned
int sleep (
unsigned
int __seconds)
;
extern
int usleep (__useconds_t __useconds)
;
sleep()
函式的功能是把呼叫該函式的執行緒掛起一段時間,單位是秒(s);
usleep()
函式的功能是把呼叫該函式的執行緒掛起一段時間 ,單位是毫秒(ms)。
四、windows相關函式
4.1 _beginthreadex 與 _endthreadex
_crtimp __cdecl __mingw_nothrow unsigned
long _beginthreadex
(void*,
unsigned
,unsigned
(__stdcall *)(
void*)
,void*,
unsigned
,unsigned*)
;
4.2 waitforsingleobject_beginthreadex
用於建立乙個後台執行緒並即刻執行,直到執行結束或者呼叫_endthreadex
函式終止執行緒。
_beginthreadex引數說明 :
C語言多執行緒程式設計基礎
我們進行多執行緒程式設計,可以有多種選擇,可以使用windowsapi,如果你在使用gtk,也可以使用gtk實現了的執行緒庫,如果你想讓你的程式有更多的移植性你最好是選擇posix中的pthread函式庫,我的程式是在linux下寫的,所以我使用了pthread庫 是不是很傷心,我知道有不少人期待的...
linux下C語言多執行緒程式設計
include include include include define max 10pthread t thread 2 pthread mutex t mut int number 0 i void thread1 printf thread1 主函式在等我完成任務嗎?n pthread e...
多執行緒程式設計 c語言linux下
適用與linux系統 1.了解基本概念 程序 是計算機所執行的乙個任務的描述,是面向作業系統的最小單位,作業系統能執行很多程序 執行自己寫的乙份 程式,就是讓作業系統執行乙個自己程式的程序 作業系統會根據程式分配定量的資源 執行緒 面想程式 程序 的,把乙個程式分成多個執行緒可以實現並髮式,多工執行...