多线程操作两个vector

jack_leiwin 2013-09-07 10:42:17
#include<iostream>
#include<Windows.h>
#include<vector>
#include<fstream>
using namespace std;

fstream out;

int k=0;

HANDLE mutex;

struct parallelBlock
{
vector<int> *arr;
vector<int> *brr;
int *temp;
int *threadNum;
};

DWORD WINAPI threadInterface(PVOID lpParameter)
{
WaitForSingleObject(mutex,INFINITE);
parallelBlock *pb=(parallelBlock*)lpParameter;
*(pb->threadNum)=*(pb->threadNum)+1;

cout<<__LINE__<<"pb->arr->size:"<<pb->arr->size()<<endl;
cout<<"k:"<<k<<endl;

k=k+1;
for(int i=0;i<100;i++)
out<<"k:"<<k<<" "<<i<<endl;

cout<<"pb->arr->size:"<<pb->arr->size()<<endl;
pb->brr->push_back(*(pb->temp));
ReleaseMutex(mutex);
*pb->threadNum=*pb->threadNum-1;
delete pb;
return 0;
}


void writeBVector(vector<int> *ve)
{
cout<<"********************"<<endl;
for(int i=0;i<ve->size();i++)
cout<<"ve["<<i<<"]="<<(*ve)[i]<<endl;
}
int main()
{
int threadNum=0;

out.open("info.txt",ios::out);
vector<int> ar;
vector<int> br;
ar.push_back(333);
ar.push_back(444);
ar.push_back(555);

mutex=CreateMutex(NULL,FALSE,NULL);

while(ar.size()>0||threadNum>0)
{
if(ar.size()>0)
{
WaitForSingleObject(mutex,INFINITE);
vector<int>::iterator ite=ar.begin();
std::cout<<"*ite:"<<*ite<<endl;

parallelBlock *pb=new parallelBlock;

pb->arr=&ar;
pb->brr=&br;
pb->temp=&(*ite);
pb->threadNum=&threadNum;

ar.erase(ite);


std::cout<<"temp:"<<*(pb->temp)<<endl;
ReleaseMutex(mutex);
CreateThread(NULL,0,threadInterface,pb,0,NULL);

}
}


Sleep(1500);

cout<<"br:size"<<br.size()<<endl;
cout<<"threadNum:"<<threadNum<<endl;
cout<<"ar.size:"<<ar.size()<<endl;
writeBVector(&br);
return 0;
}


我的目的是通过多线程将vector ar里面的元素全部移到vector br里面,但是结果却如下(划横线出表示不理解,问什么我设置了mutex,怎么还会有冲突呢?再说了,我的ite 和 pb都是局部变量啊,应该每一次循环都有新值的啊?)


请给位大神多多指教!
...全文
248 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
有新工作否 2013-09-09
  • 打赏
  • 举报
回复
引用 楼主 jack_leiwin 的回复:
#include<iostream>
#include<Windows.h>
#include<vector>
#include<fstream>
using namespace std;

fstream out;

int k=0;

HANDLE mutex;

struct parallelBlock
{
	vector<int> *arr;
	vector<int> *brr;
	int *temp;
	int *threadNum;
};

DWORD WINAPI threadInterface(PVOID lpParameter)
{
	WaitForSingleObject(mutex,INFINITE);
	parallelBlock *pb=(parallelBlock*)lpParameter;
	*(pb->threadNum)=*(pb->threadNum)+1;

	cout<<__LINE__<<"pb->arr->size:"<<pb->arr->size()<<endl;
	cout<<"k:"<<k<<endl;

	k=k+1;
	for(int i=0;i<100;i++)
		out<<"k:"<<k<<" "<<i<<endl;

	cout<<"pb->arr->size:"<<pb->arr->size()<<endl;
	pb->brr->push_back(*(pb->temp));
	ReleaseMutex(mutex);
	*pb->threadNum=*pb->threadNum-1;
	delete pb;
	return 0;
}


void writeBVector(vector<int> *ve)
{
	cout<<"********************"<<endl;
	for(int i=0;i<ve->size();i++)
		cout<<"ve["<<i<<"]="<<(*ve)[i]<<endl;
}
int main()
{
	int threadNum=0;

	out.open("info.txt",ios::out);
	vector<int> ar;
	vector<int> br;
	ar.push_back(333);
	ar.push_back(444);
	ar.push_back(555);

	mutex=CreateMutex(NULL,FALSE,NULL);
	
	while(ar.size()>0||threadNum>0)
	{
		if(ar.size()>0)
		{
			WaitForSingleObject(mutex,INFINITE);
			vector<int>::iterator ite=ar.begin();
			std::cout<<"*ite:"<<*ite<<endl;

			parallelBlock *pb=new parallelBlock;
		
			pb->arr=&ar;
			pb->brr=&br;
			pb->temp=&(*ite);
			pb->threadNum=&threadNum;

			ar.erase(ite);
		
			
			std::cout<<"temp:"<<*(pb->temp)<<endl;
			ReleaseMutex(mutex);
			CreateThread(NULL,0,threadInterface,pb,0,NULL);

		}
	}

	
	Sleep(1500);
	
	cout<<"br:size"<<br.size()<<endl;
	cout<<"threadNum:"<<threadNum<<endl;
	cout<<"ar.size:"<<ar.size()<<endl;
	writeBVector(&br);
	return 0;
}
我的目的是通过多线程将vector ar里面的元素全部移到vector br里面,但是结果却如下(划横线出表示不理解,问什么我设置了mutex,怎么还会有冲突呢?再说了,我的ite 和 pb都是局部变量啊,应该每一次循环都有新值的啊?) 请给位大神多多指教!
想不通,为什么不用c++11的thread或者boost的thread,最好不要交叉使用吧,要么就纯粹的c++,要么就纯粹的vc++。这样一半一半,没问题也变得有问题了。
lm_whales 2013-09-09
  • 打赏
  • 举报
回复
引用 4 楼 jack_leiwin 的回复:
[quote=引用 3 楼 lm_whales 的回复:] struct threadsParam{ vector<int>::iterator srcIterbegin,srcInterend; vector<int>::iterator dstIterbegin,dstIterend; }; 把这个结构传递到线程函数内部,作为线程参数使用即可 注意不要改变vector的大小,也不线程越界访问数据
大神,为什么不能改变vector的大小呢?[/quote] 改变vector的大小 iterator 极有可能失效,多线程操作非常危险。 如果,非要多线程,而且还要改变大小,或者两个线程,可能会操作同一个数据(写),必须加锁 如果要改变大小,就不能用安全的使用iterator了 。 直接当作数组好了,并且,操作每一个数据都要加锁,而且要检查数据是否越界访问。 PS : 这样,反而不如单线程方便。
赵4老师 2013-09-09
  • 打赏
  • 举报
回复
//循环向a函数每次发送200个字节长度(这个是固定的)的buffer,
//a函数中需要将循环传进来的buffer,组成240字节(也是固定的)的新buffer进行处理,
//在处理的时候每次从新buffer中取两个字节打印
#ifdef WIN32
    #pragma warning(disable:4996)
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef WIN32
    #include <windows.h>
    #include <process.h>
    #include <io.h>
    #define  MYVOID             void
    #define  vsnprintf          _vsnprintf
#else
    #include <unistd.h>
    #include <sys/time.h>
    #include <pthread.h>
    #define  CRITICAL_SECTION   pthread_mutex_t
    #define  MYVOID             void *
#endif
//Log{
#define MAXLOGSIZE 20000000
#define MAXLINSIZE 16000
#include <time.h>
#include <sys/timeb.h>
#include <stdarg.h>
char logfilename1[]="MyLog1.log";
char logfilename2[]="MyLog2.log";
static char logstr[MAXLINSIZE+1];
char datestr[16];
char timestr[16];
char mss[4];
CRITICAL_SECTION cs_log;
FILE *flog;
#ifdef WIN32
void Lock(CRITICAL_SECTION *l) {
    EnterCriticalSection(l);
}
void Unlock(CRITICAL_SECTION *l) {
    LeaveCriticalSection(l);
}
void sleep_ms(int ms) {
    Sleep(ms);
}
#else
void Lock(CRITICAL_SECTION *l) {
    pthread_mutex_lock(l);
}
void Unlock(CRITICAL_SECTION *l) {
    pthread_mutex_unlock(l);
}
void sleep_ms(int ms) {
    usleep(ms*1000);
}
#endif
void LogV(const char *pszFmt,va_list argp) {
    struct tm *now;
    struct timeb tb;

    if (NULL==pszFmt||0==pszFmt[0]) return;
    vsnprintf(logstr,MAXLINSIZE,pszFmt,argp);
    ftime(&tb);
    now=localtime(&tb.time);
    sprintf(datestr,"%04d-%02d-%02d",now->tm_year+1900,now->tm_mon+1,now->tm_mday);
    sprintf(timestr,"%02d:%02d:%02d",now->tm_hour     ,now->tm_min  ,now->tm_sec );
    sprintf(mss,"%03d",tb.millitm);
    printf("%s %s.%s %s",datestr,timestr,mss,logstr);
    flog=fopen(logfilename1,"a");
    if (NULL!=flog) {
        fprintf(flog,"%s %s.%s %s",datestr,timestr,mss,logstr);
        if (ftell(flog)>MAXLOGSIZE) {
            fclose(flog);
            if (rename(logfilename1,logfilename2)) {
                remove(logfilename2);
                rename(logfilename1,logfilename2);
            }
        } else {
            fclose(flog);
        }
    }
}
void Log(const char *pszFmt,...) {
    va_list argp;

    Lock(&cs_log);
    va_start(argp,pszFmt);
    LogV(pszFmt,argp);
    va_end(argp);
    Unlock(&cs_log);
}
//Log}
#define ASIZE    200
#define BSIZE    240
#define CSIZE      2
char Abuf[ASIZE];
char Cbuf[CSIZE];
CRITICAL_SECTION cs_HEX ;
CRITICAL_SECTION cs_BBB ;
struct FIFO_BUFFER {
    int  head;
    int  tail;
    int  size;
    char data[BSIZE];
} BBB;
int No_Loop=0;
void HexDump(int cn,char *buf,int len) {
    int i,j,k;
    char binstr[80];

    Lock(&cs_HEX);
    for (i=0;i<len;i++) {
        if (0==(i%16)) {
            sprintf(binstr,"%03d %04x -",cn,i);
            sprintf(binstr,"%s %02x",binstr,(unsigned char)buf[i]);
        } else if (15==(i%16)) {
            sprintf(binstr,"%s %02x",binstr,(unsigned char)buf[i]);
            sprintf(binstr,"%s  ",binstr);
            for (j=i-15;j<=i;j++) {
                sprintf(binstr,"%s%c",binstr,('!'<buf[j]&&buf[j]<='~')?buf[j]:'.');
            }
            Log("%s\n",binstr);
        } else {
            sprintf(binstr,"%s %02x",binstr,(unsigned char)buf[i]);
        }
    }
    if (0!=(i%16)) {
        k=16-(i%16);
        for (j=0;j<k;j++) {
            sprintf(binstr,"%s   ",binstr);
        }
        sprintf(binstr,"%s  ",binstr);
        k=16-k;
        for (j=i-k;j<i;j++) {
            sprintf(binstr,"%s%c",binstr,('!'<buf[j]&&buf[j]<='~')?buf[j]:'.');
        }
        Log("%s\n",binstr);
    }
    Unlock(&cs_HEX);
}
int GetFromRBuf(int cn,CRITICAL_SECTION *cs,FIFO_BUFFER *fbuf,char *buf,int len) {
    int lent,len1,len2;

    lent=0;
    Lock(cs);
    if (fbuf->size>=len) {
        lent=len;
        if (fbuf->head+lent>BSIZE) {
            len1=BSIZE-fbuf->head;
            memcpy(buf     ,fbuf->data+fbuf->head,len1);
            len2=lent-len1;
            memcpy(buf+len1,fbuf->data           ,len2);
            fbuf->head=len2;
        } else {
            memcpy(buf     ,fbuf->data+fbuf->head,lent);
            fbuf->head+=lent;
        }
        fbuf->size-=lent;
    }
    Unlock(cs);
    return lent;
}
MYVOID thdB(void *pcn) {
    char        *recv_buf;
    int          recv_nbytes;
    int          cn;
    int          wc;
    int          pb;

    cn=(int)pcn;
    Log("%03d thdB              thread begin...\n",cn);
    while (1) {
        sleep_ms(10);
        recv_buf=(char *)Cbuf;
        recv_nbytes=CSIZE;
        wc=0;
        while (1) {
            pb=GetFromRBuf(cn,&cs_BBB,&BBB,recv_buf,recv_nbytes);
            if (pb) {
                Log("%03d recv %d bytes\n",cn,pb);
                HexDump(cn,recv_buf,pb);
                sleep_ms(1);
            } else {
                sleep_ms(1000);
            }
            if (No_Loop) break;//
            wc++;
            if (wc>3600) Log("%03d %d==wc>3600!\n",cn,wc);
        }
        if (No_Loop) break;//
    }
#ifndef WIN32
    pthread_exit(NULL);
#endif
}
int PutToRBuf(int cn,CRITICAL_SECTION *cs,FIFO_BUFFER *fbuf,char *buf,int len) {
    int lent,len1,len2;

    Lock(cs);
    lent=len;
    if (fbuf->size+lent>BSIZE) {
        lent=BSIZE-fbuf->size;
    }
    if (fbuf->tail+lent>BSIZE) {
        len1=BSIZE-fbuf->tail;
        memcpy(fbuf->data+fbuf->tail,buf     ,len1);
        len2=lent-len1;
        memcpy(fbuf->data           ,buf+len1,len2);
        fbuf->tail=len2;
    } else {
        memcpy(fbuf->data+fbuf->tail,buf     ,lent);
        fbuf->tail+=lent;
    }
    fbuf->size+=lent;
    Unlock(cs);
    return lent;
}
MYVOID thdA(void *pcn) {
    char        *send_buf;
    int          send_nbytes;
    int          cn;
    int          wc;
    int           a;
    int          pa;

    cn=(int)pcn;
    Log("%03d thdA              thread begin...\n",cn);
    a=0;
    while (1) {
        sleep_ms(100);
        memset(Abuf,a,ASIZE);
        a=(a+1)%256;
        if (16==a) {No_Loop=1;break;}//去掉这句可以让程序一直循环直到按Ctrl+C或Ctrl+Break或当前目录下存在文件No_Loop
        send_buf=(char *)Abuf;
        send_nbytes=ASIZE;
        Log("%03d sending %d bytes\n",cn,send_nbytes);
        HexDump(cn,send_buf,send_nbytes);
        wc=0;
        while (1) {
            pa=PutToRBuf(cn,&cs_BBB,&BBB,send_buf,send_nbytes);
            Log("%03d sent %d bytes\n",cn,pa);
            HexDump(cn,send_buf,pa);
            send_buf+=pa;
            send_nbytes-=pa;
            if (send_nbytes<=0) break;//
            sleep_ms(1000);
            if (No_Loop) break;//
            wc++;
            if (wc>3600) Log("%03d %d==wc>3600!\n",cn,wc);
        }
        if (No_Loop) break;//
    }
#ifndef WIN32
    pthread_exit(NULL);
#endif
}
int main() {
#ifdef WIN32
    InitializeCriticalSection(&cs_log);
    InitializeCriticalSection(&cs_HEX );
    InitializeCriticalSection(&cs_BBB );
#else
    pthread_t threads[2];
    int threadsN;
    int rc;
    pthread_mutex_init(&cs_log,NULL);
    pthread_mutex_init(&cs_HEX,NULL);
    pthread_mutex_init(&cs_BBB,NULL);
#endif
    Log("Start===========================================================\n");

    BBB.head=0;
    BBB.tail=0;
    BBB.size=0;

#ifdef WIN32
    _beginthread((void(__cdecl *)(void *))thdA,0,(void *)1);
    _beginthread((void(__cdecl *)(void *))thdB,0,(void *)2);
#else
    threadsN=0;
    rc=pthread_create(&(threads[threadsN++]),NULL,thdA,(void *)1);if (rc) Log("%d=pthread_create %d error!\n",rc,threadsN-1);
    rc=pthread_create(&(threads[threadsN++]),NULL,thdB,(void *)2);if (rc) Log("%d=pthread_create %d error!\n",rc,threadsN-1);
#endif

    if (!access("No_Loop",0)) {
        remove("No_Loop");
        if (!access("No_Loop",0)) {
            No_Loop=1;
        }
    }
    while (1) {
        sleep_ms(1000);
        if (No_Loop) break;//
        if (!access("No_Loop",0)) {
            No_Loop=1;
        }
    }
    sleep_ms(3000);
    Log("End=============================================================\n");
#ifdef WIN32
    DeleteCriticalSection(&cs_BBB );
    DeleteCriticalSection(&cs_HEX );
    DeleteCriticalSection(&cs_log);
#else
    pthread_mutex_destroy(&cs_BBB);
    pthread_mutex_destroy(&cs_HEX);
    pthread_mutex_destroy(&cs_log);
#endif
    return 0;
}
赵4老师 2013-09-09
  • 打赏
  • 举报
回复
仅供参考
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef WIN32
    #include <windows.h>
    #include <io.h>
#else
    #include <unistd.h>
    #include <sys/time.h>
    #include <pthread.h>
    #define  CRITICAL_SECTION   pthread_mutex_t
    #define  _vsnprintf         vsnprintf
#endif
//Log{
#define MAXLOGSIZE 20000000
#define MAXLINSIZE 16000
#include <time.h>
#include <sys/timeb.h>
#include <stdarg.h>
char logfilename1[]="MyLog1.log";
char logfilename2[]="MyLog2.log";
static char logstr[MAXLINSIZE+1];
char datestr[16];
char timestr[16];
char mss[4];
CRITICAL_SECTION cs_log;
FILE *flog;
#ifdef WIN32
void Lock(CRITICAL_SECTION *l) {
    EnterCriticalSection(l);
}
void Unlock(CRITICAL_SECTION *l) {
    LeaveCriticalSection(l);
}
#else
void Lock(CRITICAL_SECTION *l) {
    pthread_mutex_lock(l);
}
void Unlock(CRITICAL_SECTION *l) {
    pthread_mutex_unlock(l);
}
#endif
void LogV(const char *pszFmt,va_list argp) {
    struct tm *now;
    struct timeb tb;

    if (NULL==pszFmt||0==pszFmt[0]) return;
    _vsnprintf(logstr,MAXLINSIZE,pszFmt,argp);
    ftime(&tb);
    now=localtime(&tb.time);
    sprintf(datestr,"%04d-%02d-%02d",now->tm_year+1900,now->tm_mon+1,now->tm_mday);
    sprintf(timestr,"%02d:%02d:%02d",now->tm_hour     ,now->tm_min  ,now->tm_sec );
    sprintf(mss,"%03d",tb.millitm);
    printf("%s %s.%s %s",datestr,timestr,mss,logstr);
    flog=fopen(logfilename1,"a");
    if (NULL!=flog) {
        fprintf(flog,"%s %s.%s %s",datestr,timestr,mss,logstr);
        if (ftell(flog)>MAXLOGSIZE) {
            fclose(flog);
            if (rename(logfilename1,logfilename2)) {
                remove(logfilename2);
                rename(logfilename1,logfilename2);
            }
        } else {
            fclose(flog);
        }
    }
}
void Log(const char *pszFmt,...) {
    va_list argp;

    Lock(&cs_log);
    va_start(argp,pszFmt);
    LogV(pszFmt,argp);
    va_end(argp);
    Unlock(&cs_log);
}
//Log}
int main(int argc,char * argv[]) {
    int i;
#ifdef WIN32
    InitializeCriticalSection(&cs_log);
#else
    pthread_mutex_init(&cs_log,NULL);
#endif
    for (i=0;i<10000;i++) {
        Log("This is a Log %04d from FILE:%s LINE:%d\n",i, __FILE__, __LINE__);
    }
#ifdef WIN32
    DeleteCriticalSection(&cs_log);
#else
    pthread_mutex_destroy(&cs_log);
#endif
    return 0;
}
//1-78行添加到你带main的.c或.cpp的那个文件的最前面
//81-85行添加到你的main函数开头
//89-93行添加到你的main函数结束前
//在要写LOG的地方仿照第87行的写法写LOG到文件MyLog1.log中
jack_leiwin 2013-09-08
  • 打赏
  • 举报
回复
引用 3 楼 lm_whales 的回复:
struct threadsParam{ vector<int>::iterator srcIterbegin,srcInterend; vector<int>::iterator dstIterbegin,dstIterend; }; 把这个结构传递到线程函数内部,作为线程参数使用即可 注意不要改变vector的大小,也不线程越界访问数据
大神,为什么不能改变vector的大小呢?
lm_whales 2013-09-08
  • 打赏
  • 举报
回复
struct threadsParam{ vector<int>::iterator srcIterbegin,srcInterend; vector<int>::iterator dstIterbegin,dstIterend; }; 把这个结构传递到线程函数内部,作为线程参数使用即可 注意不要改变vector的大小,也不线程越界访问数据
modyaj 2013-09-08
  • 打赏
  • 举报
回复
mutex 不能解决多线程同步的问题 详细的可以参看MoreWindows博客 秒杀多线程中的mutex 部分 他解释得挺好
jack_leiwin 2013-09-08
  • 打赏
  • 举报
回复
大神都哪儿去啦?

64,687

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧