如何在 c 中创建具有连续 ID 的线程?

How to create threads in c with contiguous ids?

我正在尝试在 C 中创建具有连续 ID 号的线程。 例如,假设我想创建 10 个线程,然后我想给它们 id 从 1 到 10。稍后,我希望能够访问这些 id 并从线程函数中打印出来。这可行吗?

我知道这可能看起来很简单,但我还没有设法在任何地方找到解决方案。

谢谢

线程 ID 由 OS 或线程库创建。你无法控制它们会变成什么样子。

您不需要 ID 是连续的。创建一个数组并将每个线程的 ID 存储在数组中。然后就可以使用数组依次访问了。

类似这样的事情(假设您使用 pthreads):

pthread_t thread_list[100];
int thread_count = 0;

...

pthread_create(&thread_list[thread_count++], NULL, thread_function, NULL);