我正在尝试在单独的线程中处理向量的元素并将结果放入不同的向量中。我已经尝试过使用互斥锁和代码周围的关键部分,我在其中检查并从输入向量中取出元素,但是当我运行代码时我遇到了访问冲突。
编辑:我更新了代码以将结果放回不同关键部分的向量中,并在线程启动之前初始化向量。
#include "stdafx.h"
#include <windows.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <conio.h>
#include <process.h>
#include <iostream>
#include <vector>
#define MAX_THREADS 4
void InvertProc( void * MyID ); // Threads 2 to n: display
void ShutDown( void ); // Program shutdown
int ThreadNr; // Number of threads started
CRITICAL_SECTION cs, cs2;
std::vector<int> _oTempVector;
std::vector<int> _oOutVector;
int OutCounter;
int _tmain(int argc, _TCHAR* argv[])
{
ThreadNr = 0;
OutCounter = 0;
for ( int i = 0; i < 50000; i++ ) {
_oTempVector.push_back( i );
_oOutVector.push_back( 0 );
}
InitializeCriticalSection( &cs );
InitializeCriticalSection( &cs2 );
std::vector<HANDLE> events;
for ( ThreadNr = 0; ThreadNr < MAX_THREADS; ThreadNr++ ) {
HANDLE handle = (HANDLE)_beginthread( InvertProc, 0, &ThreadNr );
events.push_back( handle );
}
WaitForMultipleObjects( events.size(), &events[0], true, INFINITE );
std::cout << "outvector contains:" << _oOutVector.size() << "elements";
std::cout << '\n';
}
void InvertProc( void *pMyID )
{
do {
EnterCriticalSection( &cs );
if ( _oTempVector.size() > 0 ) {
int iElement = _oTempVector.back();
_oTempVector.pop_back();
LeaveCriticalSection( &cs );
iElement *= -1;
EnterCriticalSection( &cs2 );
_oOutVector[OutCounter] = iElement;
OutCounter++;
LeaveCriticalSection( &cs2 );
}
} while ( _oTempVector.size() > 0 );
}