Multithreading 为什么线程id创建不按顺序?
我尝试创建10个线程,并输出每个线程索引。我的代码如下所示,我想知道为什么它们会重复而不是按顺序排列Multithreading 为什么线程id创建不按顺序?,multithreading,unix,Multithreading,Unix,我尝试创建10个线程,并输出每个线程索引。我的代码如下所示,我想知道为什么它们会重复而不是按顺序排列 #include <stdio.h> #include <pthread.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include "uti
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include "util.h"
#include <errno.h>
#include <unistd.h>
#include <signal.h>
#include <time.h>
pthread_mutex_t request_buf_lock = PTHREAD_MUTEX_INITIALIZER;
void * worker(void *arg)
{
int thread_id = *(int*)arg;
// int requests_handled = 0;
//requests_handled = requests_handled + 1;
printf("%d\n",thread_id);
}
int main(int argc, char** argv)
{
pthread_t dispatchers[100];
pthread_t workers[100];
int i;
int * thread_id = malloc(sizeof(int));
for (i = 0; i < 10; i++) {
*thread_id = i;
pthread_create(&workers[i], NULL, worker, (void*)thread_id);
}
for (i = 0; i < 10; i++) {
pthread_join(workers[i], NULL);
}
return 0;
}
#包括
#包括
#包括
#包括
#包括
#包括
#包括
#包括“util.h”
#包括
#包括
#包括
#包括
pthread\u mutex\u t request\u buf\u lock=pthread\u mutex\u初始值设定项;
void*工作者(void*arg)
{
int thread_id=*(int*)arg;
//int请求_handled=0;
//请求已处理=请求已处理+1;
printf(“%d\n”,线程id);
}
int main(int argc,字符**argv)
{
pthread_t dispatchers[100];
pthread_t workers[100];
int i;
int*thread_id=malloc(sizeof(int));
对于(i=0;i<10;i++){
*线程_id=i;
pthread_创建(&workers[i],NULL,worker,(void*)线程id);
}
对于(i=0;i<10;i++){
pthread_join(workers[i],NULL);
}
返回0;
}
输出结果为:
4.
5.
5.
6.
6.
6.
7.
8.
9
九,
但我认为它是:
0
1.
2.
3.
4.
5.
6.
7.
8.
九,
有人有什么想法或建议吗?所有10个线程并行执行,它们都共享一个
int
对象,即通过调用malloc
创建的对象
当第一个线程执行其printf
调用时,*thread\u id
的值已设置为4
。当*thread\u id
设置为5
时,第二个和第三个线程执行它们的printf
调用。等等
如果您为每个线程分配一个单独的int
对象(通过在循环中移动malloc
调用,或者仅仅通过声明int
s数组),您将在每个线程中获得唯一的线程id。但它们仍然可能以任意顺序打印,因为线程之间没有同步