我正在为客户端的每个请求创建一个线程来获取服务器上的文件。线程函数通常会得到一个void指针;但我需要给它一个char指针作为参数,并希望它由线程函数填充文件名。
代码创建一个帖子:
pt_ret = pthread_create(&thread_id, NULL, getfiles, (void*) thread_buff);
pthread_join(thread_id, pt_ret);
业。线程函数:
void *getfiles(void *ptr) {
/* ... */
char buff[256]; // populating that local buffer with the file names
// ptr should be as a return of buff
}
我尝试了不同的东西,但每次线程完成后,thread_buff就变成了Q'。
答案 0 :(得分:2)
将它转换为char *,因为你知道它实际上 是一个char *:
void *getfiles(void *ptr) {
/* ... */
const char *ptr_char = (const char*)ptr;
char buff[256];
memcpy(buff, ptr_char, 256); //just as an example, check the sizes.
//you could also strcpy, that's up to you
}
或者您也可以只处理ptr指向的缓冲区而不复制它,因此在线程结束后可以访问它:
void *getfiles(void *ptr) {
/* ... */
char *buff = (char*)ptr;
/* do stuff with buff. */
}
答案 1 :(得分:0)
我认为问题是你想要使用存储在线程中的数据" buff" var线程结束后。这是不可能的,数据只是临时存在于堆栈中。
你必须传递一个char ** ptr,并用一个buff的副本填充它,如:
*ptr = strdup(buff)
将(void *)& thread_buff而不是(void *)thread_buff传递给线程函数。