简体   繁体   English

posix线程功能中的对象

[英]objects in posix thread-functions

I have got a main function like this: 我有一个这样的主要功能:

    int main(){
    ....
    Protocol SPI_conn;

    SPI_conn.omap_SPI_init();
    ....
    pthread_create(&rt_OneStep0_thread, NULL, rt_OneStep0, NULL);
    ....
    }

where SPI_conn is an object of the class Protocol and omap_SPI_init() is a method of the same class. 其中SPI_conn是协议类的对象,而omap_SPI_init()是同一类的方法。 My thread-function looks like this: 我的线程函数如下所示:

extern "C" void * rt_OneStep0(void *)
{   
while (1) {
  sem_wait(&step0_semaphore);
  SPI_do();
  sem_wait(&step0_semaphore);
  }
}

SPI_do() is also a function of the class Protocol. SPI_do()也是协议类的函数。 My question is, how can I use the object SPI_conn with the method SPI_do. 我的问题是,如何将SPI_conn对象与SPI_do方法一起使用。 Normally you can do it by reference, but here rt_OneStep0(void*) has to be defined like this, right? 通常,您可以通过引用来完成此操作,但是这里必须像这样定义rt_OneStep0(void *),对吗?

I really appreciate your help! 非常感谢您的帮助!

Absolutely, your prototypes are correct. 绝对,您的原型是正确的。 It all lies in how you can use the last parameter of pthread_create . 这一切都取决于如何使用pthread_create的最后一个参数。 It's actually a pointer to anything you want, that will be passed as the parameter to your thread's entry point (so, here, rt_OneStep0 ). 它实际上是指向您想要的任何内容的指针,该指针将作为参数传递到线程的入口点(因此,在这里为rt_OneStep0 )。

Hence, if you create your thread like this : 因此,如果您这样创建线程:

pthread_create(&rt_OneStep0_thread, NULL, rt_OneStep0, &SPI_conn);

You will receive the address of your SPI_conn object as the void* argument of your rt_OneStep0 function. 您将收到SPI_conn对象的地址,作为rt_OneStep0函数的void*参数。 You'll just have to cast it back to the proper type and you can then use it normally. 您只需要将其强制转换回正确的类型,然后就可以正常使用它了。

extern "C" void * rt_OneStep0(void *arg)
{
      Protocol *my_object = static_cast<Protocol*>(arg);   
      //... 
}

However, since you're dealing with threads and you'll be sharing an object created on your main thread, be careful about concurrency and race conditions. 但是,由于您正在处理线程,并且将共享在主线程上创建的对象,因此请注意并发和竞争条件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM