多執行緒程式設計 執行緒休眠的方式

2021-09-27 08:57:35 字數 2560 閱讀 7300

sleep/usleep的方式休眠;

pthread_cond_wait()/pthread_cond_timedwaid();

使用sleep()/usleep()會讓執行緒進入休眠,sleep的單位時 s

ss,usleep的單位是 usus

us。很多人並不建議在多執行緒中使用sleep()/usleep()進行休眠操作。說是會休眠整個程序,但是我在測試中,並沒有遇到休眠整個程序的問題。

以下用乙個例項來說明如何使用sleep/usleep休眠執行緒。

以下**中建立了兩個執行緒:thread1每隔 5s5s

5s列印一次資料,thread2每隔 1s1s

1s遇到偶數列印一次資料。

#include #include #include #include #include void *thread1(void *param)

}void *thread2(void *param)

}int main()

error = pthread_create(&pd2, null, thread2, null);

if(error)

// 釋放執行緒資源

pthread_join(pd1, null);

pthread_join(pd2, null);

return 0;

}

結果:

pthread.c: 30: thread2: 0

pthread.c: 30: thread2: 1

pthread.c: 30: thread2: 2

pthread.c: 30: thread2: 3

pthread.c: 18: thread1: 0

pthread.c: 30: thread2: 4

pthread.c: 30: thread2: 5

pthread.c: 30: thread2: 6

pthread.c: 30: thread2: 7

# `pthread_cond_wait/pthread_cond_timedwait` ---- 大家都非常推薦使用 `pthread_cond_wait/pthread_cond_timedwait`。`pthread_cond_wait/pthread_cond_timedwait`是一系列動作的集合:**解鎖**、**等待條件為true**、**加鎖**。所以使用上述兩個函式時要加鎖。 - `pthread_cond_wait`:不機時條件等待; - `pthread_cond_timedwait`:計時條件等待;

通過pthread_cond_wait/pthread_cond_timedwait改寫上述例子。

#pragma gcc diagnostic error "-std=c++11"

#include #include #include #include #include static pthread_cond_t cond; // 條件

static pthread_mutex_t mutex; // 鎖

void *thread1(void *)

}void *thread2(void *)

}}int main()

error = pthread_create(&pd2, null, thread2, null);

if(error)

// 等待執行緒結束並**執行緒資源

pthread_join(pd1, null);

pthread_join(pd2, null);

return 0;

}

結果:

test.cpp: 42: thread2: 0

test.cpp: 30: thread1: 0

test.cpp: 42: thread2: 1

test.cpp: 42: thread2: 2

test.cpp: 30: thread1: 1

test.cpp: 42: thread2: 3

test.cpp: 42: thread2: 4

test.cpp: 30: thread1: 2

test.cpp: 42: thread2: 5

test.cpp: 42: thread2: 6

test.cpp: 30: thread1: 3

test.cpp: 42: thread2: 7

test.cpp: 42: thread2: 8

test.cpp: 30: thread1: 4

test.cpp: 42: thread2: 9

test.cpp: 42: thread2: 10

test.cpp: 30: thread1: 5

test.cpp: 42: thread2: 11

多執行緒程式設計時執行緒的喚醒方式

執行緒a和執行緒b,執行緒b可以認為消費者,而執行緒a可以認為生產者。執行緒b沒有任務時便會睡 眠。執行緒a有兩種方式喚醒執行緒b 1.condition variable,即執行緒b wait乙個condition variable,而執行緒a負責對這個co ndition呼叫notify 來喚醒...

執行緒通訊方式 休眠喚醒

執行緒間通訊常用方式如下 1.object的 wait notify notifyall 2.condition的 await signal signalall 3.countdownlatch 用於某個執行緒a等待若干個其他執行緒執行完之後,它才執行 4.cyclicbarrier 一組執行緒等待...

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

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