我正在尝试在 main()
之外编写一个玩具 pthread Controller 函数。
我在将参数结构传递给 pthread_create
函数时遇到问题。本质上它什么都不输出(好吧,我们称它为“无”)。
我假设我在
pthread_create
中对指向struct wr
的指针做错了什么,而不是输出我试图输出的结构结构指针。我在这里做错了什么?我在网上看到的每个示例都在
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: %s\n", 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) 您对函数的转换是错误的:
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_exit
或return
。 pthread_exit
不返回。删除其中一个。
void* writeline (void *arg) {
struct wr writer = *(struct wr*)arg;
printf("out: %s\n", 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);
}
}
关于C - 使用 Controller 函数的 Pthreads,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32393353/