无法判断互斥锁是否启动?

Can't tell if Mutex Lock is kicking in or not?

本文关键字:是否 启动 判断      更新时间:2024-09-21

我正在做一项大学作业,任务是展示一个基本的互斥锁示例。我从未使用过任何形式的线程,所以我是一个在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是如何工作的,但我有点迷路了。有什么建议吗?

排序显示互斥锁的作用。因此,当我在函数中输出全局var时,如果没有互斥锁,它可能会无序地显示结果。

使用互斥锁运行数字范围,out看起来像:

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 failedn");
return 1;
}
for(int i = 0; i < 10; i++){
pthread_create(&threadArr[i], NULL, incByTwo, NULL);
}

pthread_join(threadArr[0], NULL);
return 0;
}