[英]Can't tell if Mutex Lock is kicking in or not?
我正在完成一項大學作業,並負責展示一個基本的互斥鎖示例。 我從來沒有使用過任何形式的線程,所以我是一個在 C++ 中使用 POSIX 線程的初學者。
我想讓程序做的是創建 1000 個線程,將全局整數增加 1000。
#include <iostream>
#include <stdlib.h>
#include <pthread.h>
#include <sys/types.h>
#include <unistd.h>
#include <thread>
pthread_t threadArr[1000];
pthread_mutex_t lock;
// Global int to increment
int numberToInc = 0;
void* incByTwo(void*)
{
pthread_mutex_lock(&lock);
for(int j = 0; j < 1000; j++){
numberToInc += 1;
}
pthread_mutex_unlock(&lock);
return NULL;
}
int main()
{
//Creates 1000 threads with incByTwo func
for(int i = 0; i < 1000; i++){
pthread_create(&threadArr[i], NULL, incByTwo, NULL);
}
std::cout << "\n" << numberToInc << "\n";
return 0;
}
下面產生了一系列不同的結果,顯然是因為線程是並發執行的,對吧?
現在,我已經通過插入讓它正常工作
for(int i = 0; i < 1000; i++){
pthread_join(threadArr[i], NULL);
}
在線程創建循環之后,然后刪除互斥鎖,它仍然有效。 我一直試圖弄清楚 pthread_join 是如何工作的,但我有點迷茫。 有什么建議嗎?
排序方式來顯示互斥鎖的作用。 因此,當我在函數中輸出全局變量時,如果沒有互斥鎖,它有可能無序顯示結果。
使用互斥鎖運行數字范圍,輸出如下所示:
1000
2000
3000
... (etc)
10000
移除互斥鎖后,輸出的順序可能會有所不同。
例如
1000
2000
4000
6000
3000
5000
7000
8000
9000
10000
雖然三個線程的最終結果是正確的,但順序是亂序的。 在這個程序的上下文中,這並不重要,但我想如果它傳遞順序不一致的值,它會把事情搞砸嗎?
pthread_t threadArr[10];
pthread_mutex_t lock;
int numberToInc = 0;
void* incByTwo(void*)
{
pthread_mutex_lock(&lock);
for(int j = 0; j < 1000; j++){
numberToInc += 1;
}
std::cout << numberToInc << "\n";
pthread_mutex_unlock(&lock);
return NULL;
}
int main()
{
if (pthread_mutex_init(&lock, NULL) != 0)
{
printf("\n mutex init failed\n");
return 1;
}
for(int i = 0; i < 10; i++){
pthread_create(&threadArr[i], NULL, incByTwo, NULL);
}
pthread_join(threadArr[0], NULL);
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.