c - Linux 上的线程程序(Posix Thread)

标签 c linux multithreading pthreads posix-api

我想使用这个Pthread API修改Linux操作系统上的多线程程序。

#include <pthread.h>
#include <stdio.h>

int sum;
void *runner(void *param);

int main(int argc, char *argv[]) {
    pthread_t tid
        pthread_attr_t attr;

    if (argc != 2) {
        fprintf(stderr, "usage: a.out <integer value>\n");
        return -1;
    }
    if (atoi(argv[1]) < 0) {
        fprintf(stderr, "%d must be >=0\n", atoi(argv[1]));
        return -1;
    }

    pthread_attr_init(&attr);
    pthread_create(&tid, &attr, runner, argv[1]);
    pthread_join(tid, NULL);

    printf("sum = %d\n", sum);
}

void *runner(void *param);
{
    int i, upper = atoi(param);
    sum = 0;

    for (i = 1; i <= upper; i++)
        sum += i;

    pthread exit(0);
}

我想将该程序更改为具有2 个线程的程序,这些线程协同工作以添加一个数字。但我不知道如何更改它,再次感谢您提供的任何帮助。对不起,因为我不擅长解释。

最佳答案

首先有 3 个错误:pthread tid 声明没有“;”,然后在 runner()* 函数声明的末尾有一个错误,并且最后但同样重要的是,最后一行缺少下划线 pthread_exit(0) 小心啊

对变量没问题:

    pthread_t tid;
    pthread_t tid2;
    pthread_attr_t attr;
    pthread_attr_t attr2;

在 ifs 之后的代码中,添加:

pthread_attr_init(&attr);
pthread_attr_init(&attr2);
pthread_create(&tid, &attr, runner, argv[1]);
pthread_create(&tid2, &attr2, runner, argv[2]); // not sure for argv[2]?

不确定 argv[2],这取决于它是否是 2 个不同的数字?

pthread_join 没有用,它们在这里仅用于暂停线程,我认为如果您希望它们并行工作,您只需要执行“pthread_create”并且它们应该并行工作(但我在我的 CS 上看到3 年前关于并行编程的类(class),它永远不会是“真正的真正的”并行,因为只有操作系统可以控制它,你需要成为某种 super 根才能真正控制线程

我是说 它不会更快,因为它不是真正的并行程序

关于c - Linux 上的线程程序(Posix Thread),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54859101/

相关文章:

multithreading - 借用检查器可以知道 Arc 何时为 "released"吗?可以暂时授予“静态生命周期”吗?

c++ - 如何在 C++ 中执行另一个 while 循环期间获取流输入

c++ - C(++) 中的 sprintf、逗号和点(以及本地化?)

c - realloc 后奇怪的字符

php - zsh : command not found laravel

android - 如何在 AOSP 中包含 util-linux?

c# - 如何杀死一个线程?

c - gcc 中的 arm 内联汇编

c++ - 外部 C 和结构方法

linux - 在具有多个接口(interface)的服务器上接收多播 (linux)