听起来您需要创建一个任务队列。即创建工作线程来完成某些任务,然后离开。如果是这样,方法是 described here。
但您真正的问题是关于在线程之间来回传递数据。函数 CreateThread 包含一个参数 LPVOID lpParameter,它就是为了实现这种能力而包含的。它是一个 void *,因此它将接受任何变量类型,包括指向数组的指针、指向结构的指针等。这允许您根据需要来回传递尽可能多或尽可能少的数据。
下面的代码 sn-p 传递一个指向数据数组的指针。这将是您感兴趣的部分
这里是创建线程的部分
hThreadArray[i] = CreateThread(
NULL, // default security attributes
0, // use default stack size
MyThreadFunction, // thread function name
pDataArray[i], // argument to thread function
0, // use default creation flags
&dwThreadIdArray[i]); // returns the thread identifier
寻找将接收和传递数据的工作函数MyThreadFunction:
这是complete, build-able code
对于 posix:
pthread_create() 还包含可通过的数据:
int pthread_create(pthread_t * thread, pthread_attr_t * attr, void * (*start_routine)(void *), void * arg); in void *arg
可以使用最后一个参数将参数传递给线程,就像在 windows 版本中一样。你想要做的还有一个函数pthread_join(),原型:
int pthread_join(pthread_t th, void **thread_return);
该函数在被调用的线程(第一个参数线程句柄)结束时用作处理程序。当线程退出时,pthread_join 中的最后一个参数可以接收数据。这些数据可能对您声明的目的有用。