【发布时间】:2019-08-25 05:46:46
【问题描述】:
我正在编写一个小型步进电机控制程序,我需要一个单独的线程来检查是否有任何电机需要更新。
我一直卡在将我的数据结构传递给 pthread_create() 并修改 test_motor2 的状态值。下面的代码应该让我知道我想要完成什么:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
typedef struct motor{
int motor_status;
} motor;
typedef struct argstruct{
int *vect;
struct motor *allmotors;
} args;
void *test(void *arg){
struct argstruct *arguments = arg;
int *a_array = arguments->vect;
a_array[0] = 80;
// HERE I GET STUCK
struct motor *motors = arguments->allmotors;
// set test_motor2 status to 1
}
int main(){
pthread_t sidethread;
struct motor test_motor;
struct motor test_motor2;
test_motor.motor_status = 0;
test_motor2.motor_status = 0;
int a[3];
a[0] = 8; a[1] = 3; a[2] = 2;
struct motor *all_motors[2];
all_motors[0] = &test_motor;
all_motors[1] = &test_motor2;
struct argstruct motors_and_a;
motors_and_a.allmotors = all_motors;
motors_and_a.vect = a;
if (pthread_create(&sidethread, NULL, test, (void *)&motors_and_a)){
printf("Thread could not be started\n");
}
pthread_join(sidethread, NULL);
// Check that a[0] has been set to 80
printf("a[0]: %d\n", a[0]);
// Check that test_motor2 status is now 1
printf("Status of test_motor2: %d\n", test_motor2.motor_status);
}
该示例适用于阵列 a,但我无法使其适用于电机。
您能帮我找到解决方案吗?
谢谢!
最大
【问题讨论】:
-
观察:如果你打算在代码中使用
struct motor和struct argstruct,那么没有理由使用typedef。但是,这与您的主要问题 100% 相切。 -
你需要
struct motor **而不是struct motor *,看我的回答
标签: c arrays pointers struct pthreads