我正在对我编写的一个短程序运行一些测试。它运行另一个程序,该程序根据我给它的输入执行一些文件操作。这个程序的全部目的是将一个大的工作包分解成较小的包以提高性能(将 10 个较小的包发送到程序的 10 个版本,而不是等待一个较大的包执行,简单的分而治之)。
问题在于,虽然我相信我已经限制了将要创建的线程数量,但我设置的测试消息表明运行的线程比应有的多得多。我真的不确定我在这里做错了什么。
代码片段:
if (finish != start){
if (sizeOfBlock != 0){
num_threads = (finish - start)/sizeOfBlock + 1;
}
else{
num_threads = (finish-start) + 1;
}
if (num_threads > 10){ // this should limit threads to 10 at most
num_threads == 10;
}
else if (finish == start){
num_threads = 1;
}
}
threads = (pthread_t *) malloc(num_threads * sizeof(pthread_t));
for (i = 0; i < num_threads; i++){
printf("Creating thread %d\n", i);
s = pthread_create(&threads[i], NULL, thread, &MaxNum);
if (s != 0)
printf("error in pthread_create\n");
if (s==0)
activethreads++;
}
while (activethreads > 0){
//printf("active threads: %d\n", activethreads);
}
pthread_exit(0);
最佳答案
此代码无用:
if (num_threads > 10){ // this should limit threads to 10 at most
num_threads == 10
}
num_threads == 10
将 num_threads
与 10
进行比较,然后将其丢弃。你想要赋值:
if (num_threads > 10){ // this should limit threads to 10 at most
num_threads = 10;
}
此外,您的代码中缺少许多;
,以后请尝试提供一个独立的编译代码示例。
关于c - 不确定为什么会产生这么多线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20955603/