多少BUGS,盡源於拷貝粘貼! 原

多線之間的數據共享,除此之外,還有信號量共享的問題。下面的代碼是有問題的。

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, 常常由於拷貝粘貼而沒有注意同名導致。

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章