无法判断互斥锁是否启动?
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是如何工作的,但我有点迷路了。有什么建议吗?
排序显示互斥锁的作用。因此,当我在函数中输出全局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;
}
相关文章:
- 如何使用C++确定应用程序是否已在窗口中启动?
- 在继承C++子项创建者开始时,是否可以不启动父创建者?
- 计时器是否从另一个线程启动?
- 由 JOB 中的进程启动的子进程是否可以将 JOB 属性设置为脱离作业?
- 对于每个线程,random_device是否以不同的状态启动?
- SetTimer (带有回调函数)是否通过启动新线程来工作?
- 有没有办法检查内存缓存是否已重新启动?
- 是否有其他方法将.dll文件从一个项目复制到我的启动项目中的可执行文件旁边
- 无论如何,是否可以确定MFC应用程序是通过PC重新启动或用户单击应用程序快捷方式开始的
- 如何判断从 CreateProcess 启动的进程是否仍在运行
- 线程是否真的在调用 std::future::get() 后启动
- 在启动C 应用程序时,如何检查MongoDB是否正在运行
- 标准C++11是否保证std::async(std::launch::asyncfunc)在单独的线程中启动func
- 是否可以在异常(SEGFAULT)错误后自动重新启动程序
- 是否可以重新启动提升::未来
- EXE 是否可以调用启动它的 DLL
- 在技术上是否可以创建 Java 虚拟机的映像文件并使用它来更快地启动 Java 应用程序
- 是否允许在同一 Sqlite 数据库连接中启动多个事务
- 在 C++/STL/MFC 应用程序启动早期发生的致命异常中,是否可以信任堆栈回溯符号名称?
- 如何使用Qt检查Web服务是否已启动