在多线程中编辑字符串
edit string in multi thread
我对C 是新的,我知道在C 0x多线程支持中很差。但是现在我必须在多线程中编辑一个字符串阀,我使用thread_mutex保护阀门。问题是程序在运行时始终核心转储。
尽管重新设计后,我找到了一个更好的解决方案,但我无法弄清楚为什么它核心。那么有人可以告诉我发生了什么事吗?代码如下
using namespace std;
const static int kThreadSize = 48;
map<string, string> gMap;
string gStr = "";
void * func(void * data)
{
while(true)
{
printf("%sn", gStr.c_str());
pthread_mutex_t m;
pthread_mutex_init(&m, NULL);
pthread_mutex_lock(&m);
gStr = gStr + "a";//core in this line
printf("%xn", &gStr);//print the address
pthread_mutex_unlock(&m);
pthread_mutex_destroy(&m);
printf("%sn", 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;
}
编辑:通过使用全局Mutex将解决Mike指向的问题。这里我不粘贴新的源代码。
我的新问题是,我也无法理解为什么在多线程中编辑字符串时会核心。由于牛或参考数?
,因为我可以看到您的utex存在问题,因为它是在方法中创建的func()
,并且它使func()
的每个线程调用创建新的sutex,每个线程都会发生在每个线程调用此方法的威胁。
正如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("%sn", gStr.c_str());
pthread_mutex_lock(&m);
gStr = gStr + "a";//core in this line
printf("%xn", &gStr);//print the address
pthread_mutex_unlock(&m);
printf("%sn", 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;
}