多執行緒的使用方式

2021-10-07 16:17:43 字數 2861 閱讀 5968

這裡我們直接使用c++11提供的庫函式來進行實現。

簡單示例**如下:

#include

#include

using

namespace std;

void

workfun()

//搶占式

intmain()

return0;

}

需要注意的幾個點:

測試**如下:

#include

#include

using

namespace std;

void

workfun

(int index)

//搶占式

intmain()

for(

int n =

0; n <

4; n++

)for

(int n =

0; n <

4; n++

) cout <<

"hello,main thread."

<< endl;

while

(true

)return0;

}

對於執行緒陣列來說,我們使用join各個執行緒之間是可以並行執行的。如果有多個執行緒物件,我們只呼叫了乙個執行緒物件的join方法,那麼所有的執行緒都會以join的方式執行,就表現為並行執行。但是,在程式執行結束前所有的執行緒物件都需要呼叫一次join方法(只能呼叫一次),否則程式會出現異常。

在上面的**中我們多個執行緒中,cout屬於共享資源,在輸出的時候很容易出問題。我們這裡使用一下鎖,保證共享資源的安全性。**如下:

#include

#include

using

namespace std;

void

workfun

(int index)

//搶占式

intmain()

for(

int n =

0; n <

4; n++

)for

(int n =

0; n <

4; n++

)while

(true

)return0;

}

為了防止上鎖後沒解鎖,於是誕生了自解鎖,原理和智慧型指標類似。

示例**:

mutex m;

int sum =0;

void

workfun

(int index)

}//搶占式

自解鎖原始碼:

// class template lock_guard

template

<

class

_mutex

>

class

lock_guard

lock_guard

(_mutex& _mtx, adopt_lock_t)

:_mymutex

(_mtx)

~lock_guard()

noexcept

lock_guard

(const lock_guard&)=

delete

; lock_guard&

operator=(

const lock_guard&)=

delete

;private

: _mutex& _mymutex;

};

對於一些基本型別,我們可以將其定義為原子型別,避免作為共享資源運算時需要使用鎖。原子型別相對於鎖,效能有很大的提公升。

示例**如下:

#include

#include

#include

//鎖#include

//原子

#include

"celltimestamp.hpp"

using

namespace std;

//原子操作 原子 分子

mutex m;

const

int tcount =4;

atomic_int sum =0;

void

workfun

(int index)

//執行緒安全 執行緒不安全

//原子操作 計算機處理命令時最小的操作單位

//cout << index << "hello,main thread." << n << endl;

}//搶占式

intmain()

celltimestamp ttime;

for(

int n =

0; n < tcount; n++

) cout << ttime.

getelapsedtimeinmillisec()

<<

",sum="

<< sum << endl;

sum =0;

ttime.

update()

;for

(int n =

0; n <

80000000

; n++

) cout << ttime.

getelapsedtimeinmillisec()

<<

",sum="

<< sum << endl;

cout <<

"hello,main thread."

<< endl;

return0;

}

多執行緒使用方式

匯入模組 import threading import time 宣告方法 def work n print 開始於 format threading.current thread name,time.ctime time.sleep n print 結束於 format threading.cu...

多執行緒 方式四使用執行緒池

方式四 使用執行緒池 class numberthread implements runnable class numberthread1 implements runnable public class threadpool 好處 1.提高響應速度 減少了建立新執行緒的時間 2.降低資源消耗 重複...

多執行緒 實現多執行緒的幾種方式

public class mythread extends thread mythread mythread1 newmythread mythread mythread2 newmythread mythread1.start mythread2.start public class mythre...