首先,您需要决定如何管理内存:是由调用者分配的内存,还是在线程函数内部分配的内存。
如果内存是由调用者分配的,那么线程函数将如下所示:
void *function(void *arg)
{
char *p = arg;
strcpy(p, "abc"); // p points to memory area allocated by thread creator
return NULL;
}
Usage:
char data[10] = "oz"; // allocate 10 bytes and initialize them with 'oz'
...
pthread_create(&thread1,NULL,function,data);
如果内存是在线程函数内部分配的,那么你需要传递指针到指针:
void *function(void *arg)
{
char **p = (char**)arg;
*p = strdup("abc"); // equivalent of malloc + strcpy
return NULL;
}
Usage:
char *data = "oz"; // data can point even to read-only area
...
pthread_create(&thread1,NULL,function,&data); // pass pointer to variable
...
free(data); // after data is not needed - free memory-