提问人:Kagura Hitoha 提问时间:11/11/2023 更新时间:11/11/2023 访问量:54
如何让线程永远记住它在 C pthread 中的哪个数字,直到被销毁?
How to let a thread remember which number it is in C pthread forever until destroyed?
问:
我必须创建多个线程并多次使用它们。我需要让每个线程记住它是第 i 个线程(而不是系统线程 ID)。因此,线程函数中需要有一个静态位置。但是,静态变量只能使用常量值启动。另一方面,由于线程被多次使用,它们的 void *arg 会随着时间的推移而变化。因此,自创造以来,他们必须永远保持他们的数字。如何做到这一点?
我尝试首先将所有线程号存储在全局数组中。但是,让每个线程记住其对应的数组索引仍然面临同样的问题。
sem_t begin_sem, finish_sem;
int thr_nums[100];
int num;
void **thr_args;
pthread_t *threads;
void *thr_func(void *arg);
struct rusage main_usage; // get usage for main thread
int create_mat_vec_mul(int thr_count)
{
int i;
num = thr_count;
thr_args = calloc((size_t) thr_count, sizeof(void *));
threads = calloc((size_t) thr_count, sizeof(pthread_t));
sem_init(begin_sem, 0, 1);
for (i = 0; i < thr_count; ++i) {
thr_nums[i] = i;
thr_args[i] = calloc(1, sizeof(void *));
thr_args[i] = thr_nums + i;
}
for (i = 0; i < thr_count; ++i) {
pthread_create(threads + i, NULL, thr_func, (void *) thr_args[i]);
pthread_join(threads[i], NULL);
}
for (i = 0; i < thr_count; ++i) {
free(thr_args[i]);
}
return 0;
}
void *thr_func(void *arg)
{
static int *this_num_ptr = arg; // this is erroneous
sem_wait(&begin_sem);
}
答: 暂无答案
评论
this_num_ptr
static
thr_args[i] = ...
thr_args[i] = ...
thr_args[i]
int
pthread_create(..., (void *) (intptr_t) i)
int this_num = (int) (intptr_t) arg;
static
static
static