【发布时间】:2015-12-03 08:26:50
【问题描述】:
我的方案是有一个主线程和数十个工作线程。工作线程将处理来自不同端口的传入消息。
我想要做的是让主线程和工作线程共享同一个映射,工作线程将数据保存到映射中(在不同的存储桶中)。并且主线程会定期对地图内容进行grep。
代码如下:
struct cStruct
{
std::map<string::string> map1;
pthread_mutex_t mutex1;
pthread_mutex_t mutex2;
};
int main(){
struct cStruct cStruct1;
while (condition){
pthread_t th;
int th_rc=pthread_create(&th,NULL,&task,(void *) &cStruct1);
}
}
void* task(void* arg){
struct cStruct cs = * (struct cStruct*) arg;
while (coming data){
if (main_thread_work){
pthread_cond_wait(&count_cond, &cs.mutex1)
}
pthread_mutex_lock(&cs.mutex1);
// add a new bucket to the map
cs.map1(thread_identifier)=processed_value;
pthread_mutex_unlock(&cs.mutex1);
}
void* main_thread_task(void* arg){
sleep(sleep_time);
main_thread_work = true;
pthread_mutex_lock(&cs.mutex1);
// main_thread reads the std::map
main_thread_work = false;
pthread_cond_broadcast(&count_cond, &cs.mutex1)
pthread_mutex_unlock(&cs.mutex1);
}
我的问题是:
为了改变地图大小,我应该使用锁来保护地图。 但是对于具有特定键更新的地图,我可以让不同的线程同时修改地图吗? (假设不会同时访问两个相同的地图桶)
对于主线程 greps 地图,我想在主线程 grep 地图内容时使用条件等待来保持所有工作线程,然后执行 pthread_cond_broadcast 以唤醒然后。问题是如果一个工作线程在 main 开始工作时更新 map,就会出现数据竞争。
请分享一些想法来帮助我改进我的设计。
编辑 1: 添加 main_thread_task()。 我要避免的是工作线程在“pthread_cond_broadcast”之后到达 pthread_cond_wait 并且逻辑出错了。
所以我在主线程广播工作线程之前错误的 main_thread_work。
【问题讨论】:
-
在结构中使用互斥锁来保护它是错误的(您需要在结构周围使用互斥锁)。
-
你的意思是我不应该在结构中包含锁吗? (我应该声明一个全局锁吗?)
-
不是全局的,而是在外部“范围”中
-
但是对于pthread_create我只能传入一个参数,除了使用结构体或全局变量还有什么办法吗?
-
@tester 不要使用线程创建来告诉线程该做什么。创建线程后告诉线程要做什么。这样就容易多了,你可以将任何你喜欢的东西传递给线程。如果您坚持在创建线程时执行此操作,请动态分配一个包含线程所需所有内容的结构,将指向该结构的指针传递给线程,并在完成后让线程删除该结构。
标签: c++ multithreading locking pthreads