多线之间的数据共享,除此以外,还有信号量共享的问题。下面的代码是有问题的。this
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, 经常因为拷贝粘贴而没有注意同名致使。code