【发布时间】:2016-10-01 21:12:39
【问题描述】:
这里有个问题,假设我需要执行一个函数 x 次来执行一些任务,但在任何给定时间只有 四个 线程可以执行它。所以线程A、B、C、D可以分别启动任务0、1、2、3。但是,任务四在其中一个线程完成之前无法启动,因此假设线程 A 完成,那么下一个任务可以由其中一个空闲线程执行。这应该重复 x 次,其中 x 是函数需要被调用的次数。
所以我使用了信号量并在它完成后加入 pthread 以确保它完成。但是,有时 main 函数在某些线程完成之前完成执行,并且 valgrind 抱怨我的 pthread_create 正在泄漏内存。我认为我正在做的方式不正确或者是一种天真的方法,因此任何解决此问题的指导或示例代码将不胜感激!这是我的代码:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
#include <pthread.h>
#include <semaphore.h>
sem_t s;
typedef struct Data Data;
struct Data {
pthread_t* a;
int index;
int j;
};
void* someFunction(void* arg){
/* Only at most num_threads should be here at once; */
sem_wait(&s);
Data* d = arg;
printf("Successfully completed task %d with thread %d\n", d->index, d->j);
sleep(2);
pthread_t* z = d->a;
free(d);
pthread_join(*z, NULL);
sem_post(&s);
return 0;
}
int main(void){
int num_task = 15; // i need to call someFunction() 9000 times
int num_threads = 4;
int j = 0;
sem_init(&s, 0, num_threads);
pthread_t thread_ids[num_threads];
for (int i = 0; i < num_task; i ++){
/*NEED TO COMPLETE num_tasks using four threads;
4 threads can run someFunction() at the same time; so one all four are currently executing someFunction(), other threads can't enter until one has completed. */
if (j == num_threads){
j = 0; // j goes 0 1 2 3 0 1 2 3 ...
}
Data* a = malloc(sizeof(Data));
a->a = thread_ids + j;
a->index = i;
a->j = j;
sem_wait(&s);
pthread_create(thread_ids + j, NULL, someFunction, a);
sem_post(&s);
j ++;
}
return 0;
}
非常感谢
【问题讨论】:
-
第一个创建线程会尝试加入自己。这是一个僵局。
标签: c concurrency pthreads semaphore