本文目錄一覽:
C語言多線程的操作步驟
線程創建
函數原型:intpthread_create(pthread_t*restrict tidp,const pthread_attr_t *restrict attr,void *(*start_rtn)(void),void *restrict arg);
返回值:若是成功建立線程返回0,否則返回錯誤的編號。
形式參數:pthread_t*restrict tidp要創建的線程的線程id指針;const pthread_attr_t *restrict attr創建線程時的線程屬性;void *(start_rtn)(void)返回值是void類型的指針函數;void *restrict arg start_rtn的形參。
線程掛起:該函數的作用使得當前線程掛起,等待另一個線程返回才繼續執行。也就是說當程序運行到這個地方時,程序會先停止,然後等線程id為thread的這個線程返回,然後程序才會斷續執行。
函數原型:intpthread_join(pthread_tthread, void **value_ptr);
參數說明如下:thread等待退出線程的線程號;value_ptr退出線程的返回值。
返回值:若成功,則返回0;若失敗,則返回錯誤號。
線程退出
函數原型:voidpthread_exit(void *rval_ptr);
獲取當前線程id
函數原型:pthread_tpthread_self(void);
互斥鎖
創建pthread_mutex_init;銷毀pthread_mutex_destroy;加鎖pthread_mutex_lock;解鎖pthread_mutex_unlock。
條件鎖
創建pthread_cond_init;銷毀pthread_cond_destroy;觸發pthread_cond_signal;廣播pthread_cond_broadcast;等待pthread_cond_wait。
C語言如何實現多線程同時運行
1、點擊菜單欄的“Project”選項卡,下拉列表的最後一項“Project options…”是對當前工程的的屬性進行設置的。
2、選擇彈出對話框中的“Compiler”選項卡。
3、將其中的“Runtime Library”的選擇改為“Multithreaded (LIB)”。
4、將看到對話框最下面的文本框中發生了一些變化,新增了“-MT”選項,這與編譯器一開始所報的錯誤提示給出的解決方案一致。
5、頁面的設置完成後,再對該源碼進行編譯時,就能愉快地看到編譯完全成功。
c語言中怎樣創建多線程?
/*這是我寫的最簡單的多線程程序,看懂不?*/
#include windows.h
#include stdio.h
//#include strsafe.h
DWORD WINAPI ThreadProc1( LPVOID lpParam )
{
int i=0,j=0;
while(1)
{
printf(“hello,this thread 1 …\n”);
//延時
for(i=0;i200000000;i++)
{
;
}
}
}
DWORD WINAPI ThreadProc2( LPVOID lpParam )
{
int i=0,j=0;
while(1)
{
printf(“hello,this thread 2 …\n”);
//延時
for(i=0;i200000000;i++)
{
;
}
}
}
void main()
{
int i=0;
//創建線程1
CreateThread(
NULL, // default security attributes
0, // use default stack size
ThreadProc1, // thread function
NULL, // argument to thread function
0, // use default creation flags
NULL); // returns the thread identifier
//創建線程2
CreateThread(
NULL, // default security attributes
0, // use default stack size
ThreadProc2, // thread function
NULL, // argument to thread function
0, // use default creation flags
NULL); // returns the thread identifier
//讓主線程進入循環,主線程若退出,子線程1,2會被系統“殺死”
while(1)
{
printf(“hello,this thread 0 …\n”);
//延時
for(i=0;i200000000;i++)
{;}
}
}
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/188769.html