调用相同函数时的线程问题 [英] Threading issue when calling same function
问题描述
我正在尝试创建给定函数的 4 个实例,但无法确定被调用的函数如何知道哪个线程调用了它.
I am trying to create 4 instances of a given function but having trouble working out how the function called knows which thread has called it.
这是在我的头文件中:
// GPIO PINS stored within structs, for each sonic range finder.
typedef struct sonicPins {
// front left pins.
int trig1;
int echo1;
// front right pins.
int trig2;
int echo2;
// rear left pins.
int trig3;
int echo3;
// rear right pins.
int trig4;
int echo4;
} args;
void* setup(void *pinsPtr);
extern int threadFunc();
这是在我的 C 文件中.
This is within my C file.
int threadFunc()
{
struct sonicPins * pins;
pthread_create(&pt1, NULL, setup, (void*) pins);
pthread_create(&pt2, NULL, setup, (void*) pins);
pthread_create(&pt3, NULL, setup, (void*) pins);
pthread_create(&pt4, NULL, setup, (void*) pins);
return 1;
}
以下代码片段的职责是设置引脚值并运行操作来管理传感器.每个传感器都有自己的回声和触发值,它们是整数.
The duty of the snippet below is to set pin value and run operations to manage a sensor. Each sensor is has its own echo and trigger values which are integers.
void* setup(void *pinsPtr)
{
struct sonicPins *ptr = pinsPtr;
int trig = 0, Echo = 0;
printf("thread id %d\n", pt1);
if (pt1 == 1993737328) {
trig = ptr->trig1;
Echo = ptr->echo1;
} else if (pt2 == 1986323568) {
trig = ptr->trig2;
Echo = ptr->trig2;
} else if (pt3 == 1977164912) {
trig = ptr->trig3;
Echo = ptr->trig3;
} else if (pt4 == 4) {
trig = ptr->trig4;
Echo = ptr->echo4;
}
…other work…
}
我是 C 的新手,确实忘记了一个线程 ID 并不总是相同的,但我不确定我可以使用什么来进行处理.你能提出一些建议吗?
I am new to C and did forget a thread ID isn't always the same, but I'm not sure what I can use to base the handling on. Can you suggest something?
推荐答案
您需要的是一个结构体数组,其中每个结构体都有一个 echo 和 trigger 值.然后将不同的数组条目传递给每个线程,这样每个线程只知道自己的 echo 和 trigger 值.
What you need is an array of structs, where each struct has one echo and trigger value. Then you pass a different array entry to each thread, so that each thread only knows its own echo and trigger values.
#include <stdio.h>
#include <pthread.h>
typedef struct sonicPins {
int trig;
int echo;
} sonicPins;
void *threadFunc( void *args )
{
sonicPins *pins = args;
printf( "trig=%d echo=%d\n", pins->trig, pins->echo );
return NULL;
}
int main( void )
{
pthread_t threadID[4];
sonicPins pinsArray[4] = { { 1, 2 }, { 4, 8 }, { 16, 32 }, { 64, 128 } };
for ( int i = 0; i < 4; i++ )
{
if ( pthread_create( &threadID[i], NULL, threadFunc, &pinsArray[i] ) != 0 )
fprintf( stderr, "pthread_create failed: %d\n", i );
}
for ( int i = 0; i < 4; i++ )
pthread_join( threadID[i], NULL );
}
这篇关于调用相同函数时的线程问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!