这个问题是对this question的跟进。我希望线程执行一些工作并按顺序将句柄传递给下一个线程。在尝试执行以下代码时,我得到了
ConsoleApplication9.exe中0x0F7C1F5F(msvcp120d.dll)的未处理异常:0xC0000005:访问冲突读取位置0x00000004。
#include "stdafx.h"
#include <iostream>
#include <thread>
#include <mutex>
#include <chrono>
#include <condition_variable>
std::mutex* m_pMutexs;
std::condition_variable* m_pCVs;
int m_pCurrentWorker;
void func(int i)
{
int cvCurrentInd = i;
std::mutex* pCurMutex = &m_pMutexs[cvCurrentInd];
std::condition_variable* pCuCV = (std::condition_variable*)(m_pCurrentWorker + i*sizeof(std::condition_variable));
std::unique_lock<std::mutex> lk(m_pMutexs[i]);
while (i != m_pCurrentWorker)
{
pCuCV->wait(lk);
}
std::cout << "entered thread " << std::this_thread::get_id() << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(rand() % 10));
std::cout << "leaving thread " << std::this_thread::get_id() << std::endl;
m_pCurrentWorker++;
lk.unlock();
pCuCV->notify_one();
}
int _tmain(int argc, _TCHAR* argv[])
{
m_pMutexs = new std::mutex[3];
m_pCVs = new std::condition_variable[3];
m_pCurrentWorker = 0;
srand((unsigned int)time(0));
std::thread t1(func,0);
std::thread t2(func,1);
std::thread t3(func,2);
t1.join();
t2.join();
t3.join();
return 0;
}
答案 0 :(得分:1)
不知道你想做什么但是
你是否将整数转换为指针?
std::condition_variable* pCuCV = (std::condition_variable*)(m_pCurrentWorker + i*sizeof(std::condition_variable));
我认为你应该写一下:
std::condition_variable* pCuCV = &m_pCVs[i];
整个功能可能是这样的:
void func(int i)
{
std::mutex* pCurMutex = &m_pMutexs[i];
std::condition_variable* pCuCV = &m_pCVs[i];
std::unique_lock<std::mutex> lk(m_pMutexs[i]);
while (i != m_pCurrentWorker) {
pCuCV->wait(lk);
}
std::cout << "entered thread " << std::this_thread::get_id() << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(rand() % 2));
std::cout << "leaving thread " << std::this_thread::get_id() << std::endl;
m_pCurrentWorker++;
lk.unlock();
if (m_pCurrentWorker > 2) {
return;
}
pCuCV = &m_pCVs[m_pCurrentWorker];
pCuCV->notify_one();
}
答案 1 :(得分:0)
我做了一些进一步的研究,似乎原始问题的代码不是线程安全的