在多线程中访问vector

两种情况:

1. 不改变vector的元素数量, 则多线程访问无冲突。

2. 改变vector的元素数量(比如push_back, erase), 则多线程访问有冲突,需要加锁。

 


#include   
#include   
#include   
#include  
#include  
using namespace std;

#pragma comment( lib,"winmm.lib" )

struct A
{
	int a;
	string b;
};

vector  vecA;
std::mutex m;
int N = 0;

//#define   TEST_READ_WRITE
#define   TEST_PUSH_DELETE

 

DWORD WINAPI ThreadFun1(LPVOID pParam)
{   


#ifdef  TEST_READ_WRITE
	
	while (1)
	{
		for (vector::const_iterator it = vecA.begin(); it != vecA.end(); ++it)
		{
			(*it)->a =  rand() % 10;
		}
	}
#endif  


#ifdef  TEST_PUSH_DELETE
	DWORD  lastTime = timeGetTime();
	//更改vector中的数据结构
	while (1)
	{
		DWORD  t = timeGetTime();

		if (t - lastTime >= 100) //  100毫秒插入一个数据
		{
			lastTime = t;

			m.lock();
			A  *pA = new A;
			pA->a = ++N;
			vecA.push_back(pA);
			m.unlock();
		}
	}
#endif  
   

	return 0;
}

DWORD WINAPI ThreadFun2(LPVOID pParam)
{

#ifdef  TEST_READ_WRITE

	while (1)
	{
		for (vector::const_iterator it = vecA.begin(); it != vecA.end();++it )
		{
			cout << "读出数据" << (*it)->b <<"  "<< (*it)->a<< endl;
		}
	}
#endif  

#ifdef  TEST_PUSH_DELETE
	//更改vector中的数据结构
	while (1)
	{
		m.lock();
		for (vector::const_iterator it = vecA.begin(); it != vecA.end(); )
		{ 
			   A  *p = (*it);
			   cout << "删除元素" << p->a << endl;
				it = vecA.erase(it); 
				delete  p;
		}    
		m.unlock();

	} 
#endif





	return 0;
}



int main()
{
#ifdef  TEST_READ_WRITE 
	for (int i = 0; i < 10; ++i)
	{
		A * p = new A;
		p->a = i;
		p->b=to_string(i);
		vecA.push_back(p);
	}
#endif

	HANDLE  h1=  CreateThread(0, 0, ThreadFun1,  NULL, 0, NULL);
	HANDLE  h2 = CreateThread(0, 0, ThreadFun2,  NULL, 0, NULL);


	HANDLE  hands[] = { h1,h2 };
	WaitForMultipleObjects(sizeof(hands) / sizeof(HANDLE), hands, true, INFINITE);

	cout << "所有线程结束!" << endl;

}

 

你可能感兴趣的:(多线程,Windows,多线程并发编程)