使用控制器函数的Pthreads



我正在尝试在main()之外编写一个玩具pthread控制器函数。

我有传递参数结构到pthread_create函数的问题。实际上,它不输出任何内容(好吧,我们称之为"nothing")。

  1. 我假设我在pthread_create中对struct wr的指针做了一些错误的事情,而不是输出结构体,我试图输出结构体指针。我哪里做错了?

  2. 我在网上看到的每个例子都在main()中实现了pthread,这只是"简单"解释的副产品,还是我应该首先这样做?

注意是的,我确实意识到两个线程池是同步启动的。这不是问题所在。

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
struct wr {
    char str[100];
    int count;
};

void writeline (struct wr writer) {
    printf("out: %sn", writer.str);
    writer.count--; //this is left over, just ignore it for now.
    pthread_exit(0);
    return NULL;
}

void controller (void (*func)(struct wr), struct wr writer, int threads){
    pthread_t *tid;
    tid = malloc(sizeof(pthread_t) * threads);
    int i;
    for (i = threads; i > 0; i--){
// Right here is where the problem starts.
        pthread_create(&tid[i], NULL, (void *) writeline, (void *) &writer); 
    }
    for (i = threads; i > 0; i--) {
        pthread_join(tid[i], NULL);
    }
}

int main () {
    struct wr writer1 = {.str = "Bop!", .count = 3};
    struct wr writer2 = {.str = "Boop!", .count = 3};
    controller(writeline, writer1, 10);
    controller(writeline, writer2, 2);
    return 0;
}

我的Makefile选项:

CC=gcc
CFLAGS=-g -Wall -pthread

1)您对函数的cast是错误的:

    pthread_create(&tid[i], NULL, (void *) writeline, (void *) &writer); 

将函数指针转换为数据指针,这是没有意义的。

2)你的索引是tid也是错误的。例如,当分配2个pthread_t元素时,有效索引是0和1。但是你的for循环访问了1和2。

3)您没有使用函数指针。所以你根本不需要传递它。

4)线程函数接受void *作为参数,而不是struct。因此,您需要更改它并通过将其强制转换回struct wr*来检索函数中的参数。

修改后的代码:

5)您需要pthread_exitreturnpthread_exit不返回。去掉其中一个。

void* writeline (void *arg) {
    struct wr writer = *(struct wr*)arg;
    printf("out: %sn", writer.str);
    return NULL;
}
void controller (struct wr writer, int threads){
    pthread_t *tid;
    tid = malloc(sizeof(pthread_t) * threads);
    int i;
    for (i = 0; i <threads; i++) {
        pthread_create(&tid[i], NULL, writeline, &writer);
    }
    for (i = 0; i <threads; i++) {
        pthread_join(tid[i], NULL);
    }
}

最新更新