[英]C - Pthreads Using a Controller Function
我試圖在main()
之外編寫一個玩具pthread控制器函數。
將參數struct傳遞到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);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.