【发布时间】:2013-11-26 22:14:03
【问题描述】:
我正在编写一个使用 pthreads 实现循环执行计划的简单小程序。我首先编写了没有 pthreads 的程序,现在正试图正确地将参数传递给 pthread_create。 我知道参数是:
int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine) (void *), void *arg);
但是将线程发送到 ttable(时间表)给我带来了困难。 现在我正在使用线程,即使我没有使用它,我也添加了 void* x 参数(是否需要此参数?)我尝试不使用任何参数并将 NULL 作为 pthread_create 的最后一个参数传入。 我目前的错误是:错误:从'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);
}
}
}
}
}
【问题讨论】:
-
使用
void one(void*)而不是void one()等,否则我认为您需要将(void *x)更改为() -
将 (void* x) 更改为 () 使我无法从 void (*)() 转换为 void()(void*) 并更改 void one()/ two()/three() to void one(void*) 给了我从 void()(void) 到 void(*)() 的无效转换
-
其实我错了——你需要包含一个参数名称,因为它是一个函数定义而不是一个声明。使用 R.. 建议的虚拟参数。
标签: c multithreading parameter-passing argument-passing void-pointers