簡體   English   中英

指針存儲在struct中時如何調用函數

[英]How to call a function when its pointer is stored in struct

在以下示例中,如何調用該函數。

我有一個結構

struct Timing_Thread_Struct {
    int SleepTime;
    void (*Timing_Function)(int);
};

我具有在其中填充結構並創建線程的功能

struct Timing_Thread_Struct timing_struct;
timing_struct.SleepTime = 30;
timing_struct.Timing_Function = ExampleFunction;
pthread_create(&delay_thread, NULL, Delay_Thread_Function, (void *)&timing_struct);
pthread_detach( delay_thread);

示例函數為

void ExampleFunction(int event) {
    //Turn on a digital channel
}

最后是我的Delay_Thread_Function

void *Delay_Thread_Function(void *arguments)
{
    struct Timing_Thread_Struct *timing_struct = arguments;
    msleep(timing_struct -> SleepTime );

    //How do i call the function here?

    pthread_exit(NULL);
    return NULL;
}

如何調用存儲在結構中的函數?

我努力了

timing_struct->Timing_Function(1);

它崩潰了。

謝謝

線程a創建struct Timing_Thread_Struct timing_struct; 並啟動線程b ,然后返回,銷毀timing_struct中的timing_struct 線程b嘗試訪問timing_struct ,該timing_struct被破壞了,並因此導致了垃圾。 假設timing_struct持續時間長於在其下創建的線程的時間,這是一個常見錯誤。

這可以通過使用pthread_join暫停執行調用線程來解決。

我測試了您的代碼,它沒有崩潰,而是很快退出了。 所以我認為這不是結構中函數指針的問題。 要自己確認,請嘗試添加pthread_join(delay_thread, NULL); 在調用pthread_detach之前,先查看它是否仍然“崩潰”或現在正在按您的初衷工作。

正如在其他答案中提到的那樣,您依賴timing_struct變量的存在,但這可能並非如此。

如果您對pthread_join -ing線程感到滿意,則應執行以下操作:

pthread_join(delay_thread, NULL); // instead of detach

查看現場示例

否則(如果必須分離),您應該以某種方式保證該結構的存在,例如,您可以進行本地復制並使用互斥量保護進程,並使用條件變量發回信號。

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <stdbool.h>

bool created = false; // it's global just to make the example minimal 
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;

struct Timing_Thread_Struct {
    int SleepTime;
    void (*Timing_Function)(int);
};    

void ExampleFunction(int event) { printf("Hi it's %d\n", event);}        

void *Delay_Thread_Function(void *arguments)
{
    pthread_mutex_lock(&mutex);
    struct Timing_Thread_Struct timing_struct = *((struct Timing_Thread_Struct*)arguments);
    created = true;
    pthread_cond_signal(&cond);
    pthread_mutex_unlock(&mutex);
    // now this thread has it's own copy of the struct so the calling thread can end safely
    timing_struct.Timing_Function(timing_struct.SleepTime);

    pthread_exit(NULL);
    return NULL;
}

int main(void){
    struct Timing_Thread_Struct timing_struct;
    pthread_t delay_thread;    
    timing_struct.SleepTime = 30;
    timing_struct.Timing_Function = ExampleFunction;
    pthread_create(&delay_thread, NULL, Delay_Thread_Function, (void *)&timing_struct);
    pthread_detach(delay_thread);


    pthread_mutex_lock(&mutex);
    while(!created){
        pthread_cond_wait(&cond, &mutex);
    }
    pthread_mutex_unlock(&mutex);
    pthread_exit(NULL);
    return 0;
}

現場例子

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM