首页 文章

将参数传递给pthread_create - 从void(*)()到void(*)(void *)的无效转换

提问于
浏览
0

我正在编写一个使用pthread实现循环执行计划的小型简单程序 . 我首先编写没有pthreads的程序,现在我正在尝试将参数正确传递给pthread_create . 我知道args是:

int pthread_create(pthread_t * thread,const pthread_attr_t * attr,void start_routine)(void *),void * arg);

但是将线程发送到ttable(时间表)给我带来了困难 . 既然我正在使用线程,我已经添加了void * x参数,即使我没有使用它(是否需要此参数?)我已经尝试不使用参数保留计划并将ptread_create作为最后一个arg传递给NULL . 我的错误是:错误:从'void()()'到'void()(void *)'[-fpermissive]}的无效转换; ^

这是代码:

#include <ctype.h>
#include <unistd.h>
#include <sys/times.h>
#include <pthread.h>

#define SLOTX   6
#define CYCLEX  4
#define SLOT_T  1000    //1 second slot time
#define NUM_THREADS 3

int tps;
int i;
int j;
int rc;
int cycle = 0;
int slot = 0;
struct tms n;

void one(void* x){
        printf("Task 1 running\n");
        sleep(1);
}

void two(void* x){
        printf("Task 2 running\n");
        sleep(1);
}

void three(void* x){
        printf("Task 3 running\n");
        sleep(1);
}

void burn(void* x){
        printf("Burn cycle\n");
        sleep(1);
}

void (*ttable[SLOTX][CYCLEX])(void* x) = {
        {one,   one,    two,    two},
        {three, three,  three,  three},
        {two,   two,    one,    one},
        {burn,  two,    two,    burn},
        {three, three,  three,  three},
        {one,   one,    two,    two}
};

main(){
        tps = sysconf(_SC_CLK_TCK);
        pthread_t thread[NUM_THREADS];
        printf("clock ticks/sec = %d\n\n", tps);
        while(1){
                printf("Starting new hyperperiod\n");
                for(slot = 0; slot<SLOTX; slot++){
                        printf("Starting new frame\n");
                        for(cycle = 0; cycle<CYCLEX; cycle++){
                                for(i = 0; i<NUM_THREADS; i++){
                                        rc = pthread_create(&thread[i], NULL, (*ttable[slot][cycle]), *(void*)j);
                                }
                        }
                }
        }

}

2 回答

  • 0

    pthread_create 的启动函数必须只使用一个 void * 类型的参数 . 你的零参数 . 修复它们以获取 void * 类型的伪参数,一切都应该没问题 .

  • 3

    使用以下内容:

    typedef void* (*ThreadFunc_t) (void *);
    ThreadFunc_t ttable[SLOTX][CYCLEX] = {
        {one,   one,    two,    two},
        {three, three,  three,  three},
        {two,   two,    one,    one},
        {burn,  two,    two,    burn},
        {three, three,  three,  three},
        {one,   one,    two,    two}
    };
    

    ...

    rc = pthread_create(&thread[i], NULL, (ttable[slot][cycle]), (void*)i);
    

    如果使用pthread_ctreate,则必须遵循其接口:int pthread_create(pthread_t * restrict tidp,const pthread_attr_t * restrict_attr,void start_rtn)(void *),void * restrict arg);

    我希望这可以帮到你!

相关问题