c - 不确定为什么会产生这么多线程

标签 c multithreading

我正在对我编写的一个短程序运行一些测试。它运行另一个程序,该程序根据我给它的输入执行一些文件操作。这个程序的全部目的是将一个大的工作包分解成较小的包以提高性能(将 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 == 10num_threads10 进行比较,然后将其丢弃。你想要赋值:

if (num_threads > 10){  // this should limit threads to 10 at most
    num_threads = 10;
}

此外,您的代码中缺少许多;,以后请尝试提供一个独立的编译代码示例。

关于c - 不确定为什么会产生这么多线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20955603/

相关文章:

c - 为什么这个 C sizeof 函数在不同的上下文中显示不同的值?

c - 如何将字符 'G' 转换为字符串 "47"(十六进制)

c - 用于写入 EBCDIC 字符数组的 fputs

java - 服务器/客户端停止 1 个线程 = 1 个客户端

c++ - 知道 .lib 是静态的还是导入的

c - 使用 strtok() 的正确方法是什么?

c# - Thread.CurrentCulture 未保存到实例变量?

Java - 4 线程在两个同步方法中操作相同的对象数据

java - 访问匿名内部类中封闭范围的成员变量

python - 输入时间限制/倒计时