您的位置:程序门 -> vc/mfc -> 进程/线程/dll



高手来看, 线程堆分配问题.


[收藏此页] [打印本页]选择字色:背景色:字体:[][][]


高手来看, 线程堆分配问题.[已结贴,结贴人:constname]
发表于:2007-05-28 09:28:54 楼主
//vc7,   为什么我用了criticalsection还会说发生访问冲突???   我是想在主线程向
//buffer   里面放字符串,   在子线程里面不断查看buffer,   如果有字符串,   就拿出来
//有其它方法也可以,   急啊.  

#include   <windows.h>
#include   <iostream>
#include   <vector>
#include   <stack>
#include   <queue>


using   namespace   std;

char   *t;
queue <char   *>   tt;
int   threadcount   =   0;
critical_section   cri;

dword   winapi   threadproc(lpvoid   lpparam)
{

char   *mt;
char   array[1000];
memset(array, '\0 ',1000);
while(1)
{
entercriticalsection(&cri);
mt=tt.front();

tt.pop();

strcpy(array,mt);
array[strlen(mt)]   =   '\0 ';

delete[]   mt;
leavecriticalsection(&cri);
cout   < <   array < <   endl;


}
return   0;

}


int   main(int   argc,   char*   argv[])
{
initializecriticalsection(&cri);
for   (int   i=0;i <1000;i++)
{

t   =   new   char[20];
memset(t, '\0 ',20);
strcpy(t,itoa(i,t,10));
entercriticalsection(&cri);
tt.push(t);
leavecriticalsection(&cri);
if   (threadcount   ==   0)
{
threadcount++;
createthread(null,0,threadproc,null,0,null);
}

}


system( "pause ");

return   0;
}
发表于:2007-05-28 09:32:541楼 得分:10
char   array[1000];作为全局变量
发表于:2007-05-28 09:42:252楼 得分:0
我试了,   仍然访问冲突,   很显然,   和那个没关系,   主线程没有访问那个资源.
发表于:2007-05-28 09:44:223楼 得分:0
问题已解决,   我忘了判断队列是否为空
#include   "stdafx.h "
#include   <windows.h>
#include   <iostream>
#include   <vector>
#include   <stack>
#include   <queue>


using   namespace   std;

char   *t;
queue <char   *>   tt;
int   threadcount   =   0;
critical_section   cri;

dword   winapi   threadproc(lpvoid   lpparam)
{

char   *mt;
char   array[1000];

memset(array, '\0 ',1000);
while(1)
{
entercriticalsection(&cri);
bool   empty   =   tt.empty();
if   (!empty)
{
mt=tt.front();

tt.pop();

strcpy(array,mt);
array[strlen(mt)]   =   '\0 ';

delete[]   mt;
}
leavecriticalsection(&cri);
if   (!empty)
{
cout   < <   array < <   endl;
}


}
return   0;

}


int   main(int   argc,   char*   argv[])
{
initializecriticalsection(&cri);
for   (int   i=0;i <1000;i++)
{

t   =   new   char[20];
memset(t, '\0 ',20);
strcpy(t,itoa(i,t,10));
entercriticalsection(&cri);
tt.push(t);
leavecriticalsection(&cri);
if   (threadcount   ==   0)
{
threadcount++;
createthread(null,0,threadproc,null,0,null);
}

}


system( "pause ");

return   0;
}
发表于:2007-05-28 09:44:554楼 得分:90
逻辑问题,
至少你在pop前没有判断stack是否为空。
发表于:2007-05-28 10:14:415楼 得分:0
问题又来了,   如果
t   =   new   char[2000];
memset(t, '\0 ',2000);
仍然会冲突
发表于:2007-05-28 10:15:386楼 得分:0
请看最新的,   如果是new   char[2000];
会冲突


快速检索

最新资讯
热门点击