请大神来看下这段代码有没有问题。多线程高手进

登疯作极 2015-09-07 10:03:43
加精
很简单的问题,生产者、消费者模型,只是这里用了一个环形缓冲区,加锁与不加有没有影响?主要问题在代码注释给出。


#include <windows.h>

#include <mutex>
#include <thread>
#include <iostream>
#include <condition_variable>

using namespace std;

template <class T>
class PBuf{
private:
T *buf;
size_t readpos;
size_t writepos;
size_t size;
mutex mtx;
public:
HANDLE towrite;
HANDLE toread;
public:
PBuf(size_t bufsize){
size = bufsize;
buf = new T[size];
if (!buf){
cout << "molloc buf failed!\n";
return;
}
readpos = 0;
writepos = 0;
towrite = CreateEvent(NULL, FALSE, FALSE, NULL);
toread = CreateEvent(NULL, FALSE, FALSE, NULL);
}
void lock(){
mtx.lock();
}
void unlock(){
mtx.unlock();
}
void write(T item)
{
buf[writepos] = item;
writepos = (writepos + 1) % size;
}
T read(){
T item = buf[readpos];
readpos = (readpos + 1) % size;
return item;
}
bool isfull(){
return (writepos+1)%size == readpos;
}
bool isempty(){
return (readpos+1)%size == writepos;
}
~PBuf(){
if (buf) delete[] buf;
}
};

PBuf<int> produceBuf(12);
PBuf<int> customBuf(6);
class Producer{

public:
static void run()
{
while (1){
//produceBuf.lock();//此处不用锁是否可行?如果用锁,应该用什么锁?
if (produceBuf.isfull())
{
cout << "producer wait\n";
WaitForSingleObject(produceBuf.towrite, INFINITE);
}
produceBuf.write(rand());
SetEvent(produceBuf.toread);
//produceBuf.unlock();
}
}
};
class Custom{

public:
static void run()
{
while (1){
//produceBuf.lock();
if (produceBuf.isempty()) WaitForSingleObject(produceBuf.toread, INFINITE);
cout << (produceBuf.read()) << endl;
SetEvent(produceBuf.towrite);
//produceBuf.unlock();
}
}
};

int main(){
thread p(Producer::run);
thread c(Custom::run);
p.join();
c.join();
system("pause");
}
...全文
740 13 打赏 收藏 转发到动态 举报
写回复
用AI写文章
13 条回复
切换为时间正序
请发表友善的回复…
发表回复
wjlsmail 2015-09-15
  • 打赏
  • 举报
回复
多线程共享全局变量,最基本也得用互斥锁保护一下。
wo_happy 2015-09-13
  • 打赏
  • 举报
回复
你的代码本身就有bug,是学生吧? 你要用空栈递增的话,写指针得初始化成1. 否则如果先调用empty,本来刚开始是empty的,但你看你返回了啥。 我估计你把主函数:thread p(Producer::run); thread c(Custom::run);掉个过,问题就出来了,我没环境我就不试了。 还有,连sleep函数都没有,这是要狂打印吗? 然后再说锁的问题。 就你这个程序,加不加锁无所谓,因为只有一个写进程和读进程。 还有,加锁你范围加那么大干嘛,你只要保证读和写的操作是原子操作即可。所以你的锁应该加在读函数和写函数里面。用啥锁,就用互斥锁即可。 就你这个程序,潜在的问题是: (1)如果栈已经满了,read中已经从buffer读了数据,但还没有加读指针,所以write函数中,会还是认为栈是满的,所以就会进入if语句。如果if中还有其他只有栈满了才执行的代码,就可能导致问题。 (2)同理,如果栈为空,write中已经往buffer里写了数据,但还 没有加写指针,read函数中同样会进入if分支。 如果有2个write函数,第一个write函数已经往buffer里写了数据,但还没有加写指针,而另外一个write函数中判断栈满的时候,因为写指针还是之前的,所以还是认为栈没满,所以第二个write函数就覆盖了第一个write函数写入的数据,并且写指针被加了2次。 如果有中断的话,问题更严重。好好理解理解吧。
tejiu26 2015-09-13
  • 打赏
  • 举报
回复
ztenv 2015-09-11
  • 打赏
  • 举报
回复
必须要加锁的,否则可能出现结果不对的问题也可能不出现,但你多个线程同时读和写了同一个资源,就要加;
raodi03 2015-09-10
  • 打赏
  • 举报
回复
linfengc 2015-09-10
  • 打赏
  • 举报
回复
readpos++ 也是多线程访问的数据? 那就也隐含的属于buffer,表示buffer的状态在改变 所以要加锁.
赵4老师 2015-09-09
  • 打赏
  • 举报
回复
用 (答案就是这么简单)
赵4老师 2015-09-08
  • 打赏
  • 举报
回复
仅供参考:
//循环向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;
}
登疯作极 2015-09-08
  • 打赏
  • 举报
回复
引用 5 楼 dustpg 的回复:
[quote=引用 4 楼 xfboy2008 的回复:] [quote=引用 1 楼 dustpg 的回复:] 是否加锁: 多线程均写同一数据 -> 必须加 多线程一写多读同一数据 -> 不在意读取错误数据可以不加, 一般得加 多线程读同一数据 -> 不用 什么锁(对于简单数据读写): 锁定时间段且多核 -> 自旋锁 否则 -> 互斥锁 这里不看核心代码, 光是std::cout就得加锁, 否则输出错误数据
像我程序这样,如果多线程读数据时有循环buf的readpos++操作,用不用加锁?[/quote] 我哪知道你指的啥, 读写同一数据就加锁[/quote] 多线程对同一环形buf进行只读操作,用不用加锁?问题就是这么简单
dustpg 2015-09-08
  • 打赏
  • 举报
回复
引用 4 楼 xfboy2008 的回复:
[quote=引用 1 楼 dustpg 的回复:] 是否加锁: 多线程均写同一数据 -> 必须加 多线程一写多读同一数据 -> 不在意读取错误数据可以不加, 一般得加 多线程读同一数据 -> 不用 什么锁(对于简单数据读写): 锁定时间段且多核 -> 自旋锁 否则 -> 互斥锁 这里不看核心代码, 光是std::cout就得加锁, 否则输出错误数据
像我程序这样,如果多线程读数据时有循环buf的readpos++操作,用不用加锁?[/quote] 我哪知道你指的啥, 读写同一数据就加锁
登疯作极 2015-09-08
  • 打赏
  • 举报
回复
引用 1 楼 dustpg 的回复:
是否加锁: 多线程均写同一数据 -> 必须加 多线程一写多读同一数据 -> 不在意读取错误数据可以不加, 一般得加 多线程读同一数据 -> 不用 什么锁(对于简单数据读写): 锁定时间段且多核 -> 自旋锁 否则 -> 互斥锁 这里不看核心代码, 光是std::cout就得加锁, 否则输出错误数据
像我程序这样,如果多线程读数据时有循环buf的readpos++操作,用不用加锁?
jiqiang01234 2015-09-08
  • 打赏
  • 举报
回复
建议楼主好好学习一下c++特有的RAII机制,对于锁的保护非常有用。还有,智能指针也得好好学,尽量不要出现delete []之类的语句
dustpg 2015-09-07
  • 打赏
  • 举报
回复
是否加锁: 多线程均写同一数据 -> 必须加 多线程一写多读同一数据 -> 不在意读取错误数据可以不加, 一般得加 多线程读同一数据 -> 不用 什么锁(对于简单数据读写): 锁定时间段且多核 -> 自旋锁 否则 -> 互斥锁 这里不看核心代码, 光是std::cout就得加锁, 否则输出错误数据

5,530

社区成员

发帖
与我相关
我的任务
社区描述
C/C++ 模式及实现
社区管理员
  • 模式及实现社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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