本程序小渣在工作过程中用到了多线程,在访问读写全局变量的时候,线程共享同一块资源,这时设置线程锁成为了必要,工作的代码需要三次循环,一个线程向全局数组中写数据,一个线程用opengl画图,开发时使用WINDOWS程序,这里的代码暂时作为一个例子,已经成功达到想要的结果,既然三次循环,由一个全局变量(数值)控制,三次循环写入全局变量数组中的的数据都不一样,而且这个全局变量也决定了开辟内存空间的大小是不同的,如果按照已知逻辑,三次循环,每次根据这个全局变量,动态开辟数组,那么会遇到画图线程在读取数据的过程中,可能循环已经到了下一次,这样重新开辟内存的话,数据也就不复存在了,达不到预期效果,这里我就尝试着改变了逻辑,只初始化一次。看代码吧
#include <windows.h>
#include <iostream>
using namespace std;
int *a;
int *a2;
int *a3;
int loop;
CRITICAL_SECTION gcc;
HANDLE hThread1,hThread2;
void g1();
void g2();
void g3();
DWORD WINAPI hThreadProc1(LPVOID lpParameter)
{
int i;
while(true)
{
for (i = 0;i<3;i++)
{
if (i ==0)
{
g1();
}
if (i ==1)
{
g2();
}
if (i==2)
{
g3();
}
}
//LeaveCriticalSection(&gcc);
}
return 0;
}
DWORD WINAPI hThreadProc2(LPVOID lpParameter)
{
int i;
while(true)
{
if (loop==1)
{
EnterCriticalSection(&gcc);
for (i =0;i<5;i++)
{
cout<<"tread_two"<<a[i]<<endl;
}
LeaveCriticalSection(&gcc);
}
if (loop==2)
{
EnterCriticalSection(&gcc);
for (i = 0;i<10;i++)
{
cout<<"tread_two"<<a2[i]<<endl;
}
LeaveCriticalSection(&gcc);
}
if (loop==3)
{
EnterCriticalSection(&gcc);
for (i = 0;i<15;i++)
{
cout<<"tread_two"<<a3[i]<<endl;
}
LeaveCriticalSection(&gcc);
}
}
return 0;
}
void g1()
{
int i;
loop = 1;
EnterCriticalSection(&gcc);
for (i=0;i<5;i++)
{
cout<<"thread1"<<endl;
a[i] = i;
}
LeaveCriticalSection(&gcc);
}
void g2()
{
int i;
loop = 2;
EnterCriticalSection(&gcc);
for (i=0;i<10;i++)
{
cout<<"thread1"<<endl;
a2[i] = i;
}
LeaveCriticalSection(&gcc);
}
void g3()
{
int i;
loop = 3;
EnterCriticalSection(&gcc);
for (i=0;i<15;i++)
{
cout<<"thread1"<<endl;
a3[i] = i;
}
LeaveCriticalSection(&gcc);
}
int main()
{
hThread1=NULL,hThread2=NULL;
a = (int *)malloc(sizeof(int)*5);
a2 = (int *)malloc(sizeof(int)*10);
a3 = (int *)malloc(sizeof(int)*15);
InitializeCriticalSection(&gcc);
hThread1=CreateThread(NULL,NULL,hThreadProc1,NULL,NULL,NULL);
hThread2=CreateThread(NULL,1,hThreadProc2,NULL,NULL,NULL);
HANDLE tHandle[]={hThread1,hThread2};
WaitForMultipleObjects(2,tHandle,true,INFINITE);
DeleteCriticalSection(&gcc);
CloseHandle(hThread1);
CloseHandle(hThread2);
return 0;
}