windows 和 linux 多執行緒

2022-09-06 14:06:18 字數 2599 閱讀 5718

學習了幾天多執行緒技術,做個總結,便於記憶。

一般 多執行緒傳遞引數 為 void*  所以會有乙個強制轉換過程  (int*) (void *)等,傳遞多個引數選擇 結構體指標。為了避免多個執行緒訪問資料衝突 會有乙個 叫做  「臨界區」criticalsection「 類 ,防止讀寫資料衝突,

大概流程是:

critical_section cs;

init cs(cs);

the one process

enter cs

le**ecs

delete(cs);

在利用多執行緒時候,會遇到資料分割的問題 一般的規定是:

假設 data = n   process_num = m;

n 能整除m 簡單  n/m

n 不能整除 m  則 m-1 個程序的資料處理數 為 n/(m-1) 最後乙個程序處理數為n - (n/(m-1)*(m-1))

一般利用全域性變數完成執行緒間的簡單通訊 。當然也有timer定時器控制線程啟動 ,和event事件觸發執行緒。

windows下 多執行緒標頭檔案為 process.h

linux下     。。。               pthread.h 另外編譯時候 加上 -lpthread

windows 新建乙個執行緒 有 createthread _beginthread (略過引數)

linux下    。。。            pthread_create

windows 凍結解凍執行緒為 suspendthread() resumethread()

linux下 。。。一般用執行緒鎖  pthread_mutex_lock   pthread_mutex_unlock

/*程式流程為:主線程建立子執行緒(當前子執行緒狀態為stop停止狀態),5秒後主執行緒喚醒子執行緒,10秒後主執行緒掛起子執行緒,15秒後主執行緒再次喚醒子執行緒,20秒後主執行緒執行完畢等待子執行緒退出。

**如下:*/

#include "stdio.h"

#include "unistd.h"

#include "pthread.h"

#include "string.h"

#include "time.h"

#define run 1

#define stop 0

pthread_mutex_t mut = pthread_mutex_initializer;

pthread_cond_t cond = pthread_cond_initializer;

int status = stop;

void * thread_function(void)

pthread_mutex_unlock(&mut);

printf("child pthread %d\n", i++);

if (i == 20)

break;

sleep(1);

}

}void thread_resume()

else

}void thread_pause()

else

}int main()

if (0 == pthread_join(child_thread, null))

printf("child thread is over\n");

return 0;

}

。。。。。涉及到執行緒間的同步與非同步一般會用到如下函式。。。。。。。。。。。。

windows 等待執行緒結束  waitforsingleobject() waitformultipleobjects()

linux 。。。   pthread_join()

windows 退出執行緒 exitthread() terminatethread()/強制結束執行緒

linux 退出執行緒  pthread_exit() 

還有關鍵的 signal 沒有學習,再update吧。

最後附上linux 和windows 多執行緒測試** 

linux : gcc test.c -fopenmp -lpthread -o test

#include "stdio.h"

#include "omp.h"

#include "time.h"

#include "unistd.h"

#include "pthread.h"

clock_t start,end;

void* test(void *p)

void* test1(void *p)

int main()

windows :

#include #include #include #include #define _crt_secure_no_warnings

using namespace std;

critical_section cs;

int i = 0;

void run(void *) }

int main()

waitforsingleobject(hd, true);

system("pause");

return 0;

}

在windows下配置pthread多執行緒

pthread是由posix提出的一套通用的執行緒庫,在linux平台下,它被廣泛的支援,而windows平台下,卻並不被支援,而pthreads w32為我們提供了解決方案,本文我們準備在我們的windows平台下進行pthread w32的安裝,在網路上有類似的文章,但是講的都是比較老的平台,在...

ThreadPoolExecutor 多執行緒

from concurrent.futures import threadpoolexecutor,wait,all completed from queue import queue myqueue queue 佇列,用於儲存函式執行結果。多執行緒的問題之一 如何儲存函式執行的結果。def thr...

c 多線例項

using system using system.threading using system.text namespace controlthread 第二個執行緒正在執行,請輸入 s uspend,r esume,i nterrupt,or e xit.datetime.now.tostrin...