我正在学习POSIX线程。目标是编写程序,创建一个线程,创建两个新线程。每个创建的线程都会生成另外两个线程。每个新线程应该睡眠,而不是告诉他的id(睡眠时间和ID变为参数),计算整体睡眠时间然后开始创建新线程。
const map = new Map();
$.each(objs, function (idx, obj) {
if(!map.has(obj.category)) {
map.set(obj.category, []);
}
map.get(obj.category).push(obj);
});
它会创建我想要的所有线程,但id不是唯一的。我正在变成这样的输出:
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#define MAX_THREADS 10
pthread_mutex_t wait_time_overall_mutex;
pthread_mutex_t threads_count_mutex;
pthread_mutex_t struct_mutex;
int wait_time_overall = 0;
int threads_count = 0;
struct threads_data {
int thread_id;
int time;
};
void* SpawnTwoThreads(void *args) {
pthread_t t1;
pthread_t t2;
struct threads_data t_args = *(struct threads_data*)args;
int this_thread_id = t_args.thread_id;
int this_time = t_args.time;
printf("t%d: Sleeping for %d\n", this_thread_id, this_time);
sleep(this_time);
pthread_mutex_lock(&wait_time_overall_mutex);
wait_time_overall = wait_time_overall + this_time;
pthread_mutex_unlock(&wait_time_overall_mutex);
printf("My id is: %d\n", this_thread_id);
if (threads_count < MAX_THREADS) {
pthread_mutex_lock(&threads_count_mutex);
threads_count++;
pthread_mutex_unlock(&threads_count_mutex);
pthread_mutex_lock(&struct_mutex);
t_args.time = rand() % 10;
t_args.thread_id = threads_count;
pthread_mutex_unlock(&struct_mutex);
pthread_create(&t1, NULL, SpawnTwoThreads, &t_args);
}
if (threads_count< MAX_THREADS) {
pthread_mutex_lock(&threads_count_mutex);
threads_count++;
pthread_mutex_unlock(&threads_count_mutex);
pthread_mutex_lock(&struct_mutex);
t_args.time = rand() % 10;
t_args.time = threads_count;
pthread_mutex_unlock(&struct_mutex);
pthread_create(&t2, NULL, SpawnTwoThreads, &t_args);
}
pthread_join(t1, NULL);
pthread_join(t2, NULL);
printf("Bye from %d\n", this_thread_id);
pthread_exit(NULL);
}
int main(void) {
pthread_t t1;
int t1_wait_time;
srand(time(NULL));
pthread_mutex_init(&threads_count_mutex, NULL);
pthread_mutex_init(&wait_time_overall_mutex, NULL);
pthread_mutex_init(&struct_mutex, NULL);
struct threads_data args;
args.thread_id = threads_count++;
args.time = rand() % 10;
pthread_create(&t1, NULL, SpawnTwoThreads, &args);
printf("In main: waiting for all threads to complete\n");
pthread_join(t1, NULL);
printf("Overall waittime is %d\n", wait_time_overall);
pthread_exit(NULL);
}
不应该排序。但至少应该是每个id都是唯一的。我用互斥锁做错了吗?在创建新线程之前,我正在更新结构变量。但它看起来并不像那样。