C 多執行緒學習入門2

2021-10-01 02:59:46 字數 1257 閱讀 4222

example5 和example6的寫法,後者的執行時間要比前者快;

在cpu進行運算時會把result的陣列中的陣列抄送到快取中,這樣每次兩個執行緒會分別的對result[0]和result[1]抄送的值進行加 1操作,但是等到快取向記憶體中寫值的時候會出現其中乙個與一開始抄送的值並且本執行緒沒有改變的那個值(被另乙個執行緒改變了)不一致,這時候會將新的值(被另乙個執行緒改變的值)再次抄送到本執行緒所在cpu的快取中,這就造成了false sharing的現象,浪費時間了。

#include

#include

using

namespace std;

#define max_size 50000000

typedef

struct

my_args;

intmain()

;for

(int i=0

;i) arr[i]

=rand()

%50;my_args args1=

;my_args args2=

;for

(int i=

0;i<

5000

;i++

)arr[i]

=rand()

%5;#if 1

//example5

auto myfunc=

[&arr,

&results]

(my_args* args)

;#else

//example6

auto myfunc=

[&arr]

(my_args* args)

;#endif

thread t1

(myfunc,

&args1)

;thread t2

(myfunc,

&args2)

;t1.

join()

;t2.

join()

;#if 1

cout<<

"s1="

<<<

"\ns2="

<<<

"\ns1+s2="

<+results[1]

<#else

cout<<

"s1="

<"\ns2="

<"\ns1+s2="

<#endif

delete

arr;

return0;

}

C 多執行緒學習2

include stdafx.h include beginthread.h ifdef debug define new debug new undef this file static char this file file endif include stdafx.h include wind...

c 多執行緒2

for int i 0 i 100000 i 這麼一段 放在程式裡的那簡直頁面會卡出蛇精病,怎麼辦呢,用多執行緒試試 private void button1 click object sender,eventargs e private void er 頁面 呵呵呵,愚蠢人類,卡死你了吧。窩 媽蛋...

Linux (C)多執行緒學習(入門)

下面兩個仁兄總結非常好。總結比較好 比較具體 例子 主要學習乙個例子 test1.c created on 2016年7月26日 author andy cong 利用多執行緒與有名管道技術,實現兩個程序之間傳送即時訊息,實現聊天功能。mkfifo xx 新建乙個管道xx 兩個程式test1 tes...