我写了下面这个简单的程序来理解线程。结果有一些垃圾字符 - 为什么会出现这些字符?我在 Fedora 17 中使用 GNU G++ 编译器。
#include <iostream>
#include <string.h>
#define THREAD_COUNT 5
struct Man
{
char name[10];
int age;
std::string address;
};
void* ThreadTask(void* man)
{
Man *my_man = (Man*)man;
std::cout << "Address of the person: " << my_man->address << std::endl;
}
int main()
{
pthread_t threads[THREAD_COUNT];
Man men_list[THREAD_COUNT];
for(int i=0; i<THREAD_COUNT; i++)
{
strcpy(men_list[i].name,"nayana");
men_list[i].age = i;
men_list[i].address = "Singapore";
int rc = pthread_create(&threads[i],NULL,ThreadTask,(void*)&men_list[i]);
if(rc)
{
std::cout << "Error while creating the thread" << std::endl;
}
}
pthread_exit(NULL);
return 0;
}
结果:
Address of the person: Singapore�0+���*��! ����Singapore�0��▒s�!��t��s���E��t��s���EI
Address of the person: Singapore�0;s��:s�!�w ����Singapore�0+���*��! ����Singapore�0��▒s�!��t��s���E��t��s���EI
Address of the person: Address of the person:
最佳答案
您需要确保所有线程在 men_list
超出范围并回收内存之前运行。
这不是 pthread_exit
所做的——而是终止调用线程。
main()
末尾的 pthread_exit(NULL)
没有完成任何有意义的事情。尽管手册页说使用 pthread_exit
退出主函数将“允许其他线程运行完成”(如您在评论中所指),但这并不意味着main 函数不会在函数结束时结束,也不意味着其他线程将在 pthread_exit
返回之前运行完成。
您可以使用pthread_join
来等待线程运行完成。要等待所有线程运行完成,您可以使用如下内容:
int main()
{
pthread_t threads[THREAD_COUNT];
Man men_list[THREAD_COUNT];
for(int i=0; i<THREAD_COUNT; i++)
{
strcpy(men_list[i].name,"nayana");
men_list[i].age = i;
men_list[i].address = "Singapore";
int rc = pthread_create(&threads[i],NULL,ThreadTask,(void*)&men_list[i]);
if(rc)
{
std::cout << "Error while creating the thread" << std::endl;
}
}
for(int i=0; i < THREAD_COUNT; i++)
{
pthread_join( threads[i], NULL );
}
return 0;
}
关于c++ - 为什么字符串变量打印有垃圾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20965597/