您的位置:首页 > 编程语言 > C语言/C++

多少BUGS,尽源于拷贝粘贴!

2016-07-30 00:00 495 查看
摘要: 通常多线程编程最大的问题是数据共享的问题,仅共享加锁列表的方法,可以很好的解决。

多线之间的数据共享,除此之外,还有信号量共享的问题。下面的代码是有问题的。

class cthread1{
void start();
void thread_proc();

private:
sem_t* psem;
};

static void *do_thread1(void* data){
cthread1* ptread = (cthread1*)data;
pthread->thread_proc();
}

void cthread1:start(){
psem = sem_open("http", O_CREAT, 0644, 1);
pthread_t thread_t;
pthread_create(&thread_t, NULL, do_thread1, this);
pthread_detach(thread_t);
}

void cthread1:thread_proc(){
//use psem,do somthing.
}

class cthread2{
void start();
void thread_proc();

private:
sem_t* psem;
};

static void *do_thread2(void* data){
cthread2* ptread = (cthread2*)data;
pthread->thread_proc();
}

void cthread2:start(){
psem = sem_open("http", O_CREAT, 0644, 1);
pthread_t thread_t;
pthread_create(&thread_t, NULL, do_thread2, this);
pthread_detach(thread_t);
}

void cthread2:thread_proc(){
//use psem,do somthing.
}

因为psem是个共享内存信号量,名字一样的话,两个类里的psem是一样的,这是个很低级的BUG, 常常由于拷贝粘贴而没有注意同名导致。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c++ 多线程 信号量