【发布时间】:2020-11-11 11:44:32
【问题描述】:
我正在完成一项大学作业,我的任务是展示一个基本的互斥锁示例。我从来没有使用过任何形式的线程,所以我是一个在 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 是如何工作的,但我有点迷茫。有什么建议吗?
【问题讨论】:
-
如果您仍然使用原始 POSIX 库,为什么还要使用 C++?
-
正在使用我用来研究操作系统中线程的书中提供的线程示例。他们都提供了使用 pthread 的示例,但我想提供我自己的示例。
-
创建一个线程需要一段时间,因此在创建下一个线程之前,第一个线程可能已经完成。将
sleep放在incByTwo的开头。 -
是的,join 是必需的,否则 main 会在你的 1000 个线程完成之前完成,你每次都会得到意想不到的部分结果
-
添加睡眠肯定有帮助,那么这是否是一个糟糕的实际示例来展示互斥锁是如何工作的,因为 sleep() 调用允许它在没有锁到位的情况下产生相同的结果?
标签: c++ multithreading pthreads mutex