我是c ++的新手,我知道在c ++ 0x中,多线程支持很差。 但是现在我必须在多线程中编辑一个字符串val,我使用thread_mutex来保护val。问题是程序在运行时始终是核心转储。
虽然经过重新设计后我找到了一个更好的解决方案,但我无法弄清楚它为什么是核心。有人可以告诉我发生了什么吗? 代码如下所示
using namespace std;
const static int kThreadSize = 48;
map<string, string> gMap;
string gStr = "";
void * func(void * data)
{
while(true)
{
printf("%s\n", gStr.c_str());
pthread_mutex_t m;
pthread_mutex_init(&m, NULL);
pthread_mutex_lock(&m);
gStr = gStr + "a";//core in this line
printf("%x\n", &gStr);//print the address
pthread_mutex_unlock(&m);
pthread_mutex_destroy(&m);
printf("%s\n", gStr.c_str());
}
}
int main()
{
pthread_t threads[kThreadSize];
for(int i = 0; i < kThreadSize; i ++)
{
pthread_create(&threads[i], NULL, &func, &gMap);
}
for(int i = 0; i < kThreadSize; i ++)
{
pthread_join(threads[i], NULL);
}
return 0;
}
编辑: 通过使用全局互斥体将解决Mike指出的问题。这里我不粘贴新的源代码。
我的新问题是我也无法理解为什么在多线程中编辑字符串时它会核心。因为COW或参考计数?
答案 0 :(得分:0)
我可以看到你的Mutex存在问题,因为它是在方法func()
中创建的,并且它使func()
的每个线程调用都创建了一个新的互斥锁,它发生在每个调用此方法的威胁。
正如MikeB所说,我很高兴你回顾一下线程理论,但同时,尝试使用一个独特的互斥锁来同步对gMap
的访问,如示例所示:
using namespace std;
const static int kThreadSize = 48;
map<string, string> gMap;
string gStr = "";
pthread_mutex_t m;
void * func(void * data)
{
while(true)
{
printf("%s\n", gStr.c_str());
pthread_mutex_lock(&m);
gStr = gStr + "a";//core in this line
printf("%x\n", &gStr);//print the address
pthread_mutex_unlock(&m);
printf("%s\n", gStr.c_str());
}
}
int main()
{
pthread_mutex_init(&m, NULL);
pthread_t threads[kThreadSize];
for(int i = 0; i < kThreadSize; i ++)
{
pthread_create(&threads[i], NULL, &func, &gMap);
}
for(int i = 0; i < kThreadSize; i ++)
{
pthread_join(threads[i], NULL);
}
return 0;
}