ant*_*009 5 c pointers pthreads function callback
c程序编译器gcc
我有3个文件.main.c stop_watch.h和stop_watch.c
这个程序确实有效.我叫start_stopwatch.并且在时间到期后它将在main.c timeout_cb()中回调.我也在一个单独的线程中运行它,因为我不想在main中阻塞,因为我将需要运行其他代码.
1)g_start_timer中的秒数总是给垃圾.我以为我可能通过在堆上创建结构来解决这个问题.无论如何我可以解决这个问题.我在考虑在堆上创建秒元素.但是认为这是过度杀戮
2)这个程序运行正常,但是如果我在main printf中注释掉这行("=== timeout_cb:%p \n",timeout_cb); 它将堆叠转储.
3)何时是释放记忆的最佳时间.我正在释放它.但我担心如果在线程完成之前释放内存.这可能会导致非常意外的结果.我想我可以在调用后使用thread_join()作为释放内存.但是,我需要返回在stop_watch.c中创建的thead_id,是否有办法返回在stop_watch.c中创建的thread_id
非常感谢任何建议,
main.c中
/* main.c */
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include "stop_watch.h"
/* call this when the time expires */
void timeout_cb()
{
printf("=== your time is up run some job here ===\n");
}
int main()
{
struct data_struct *g_data_struct =
(struct data_struct*) calloc(1, sizeof(*g_data_struct));
if(!g_data_struct)
{
printf("=== failed to allocate memory ===\n");
return 0;
}
g_data_struct->seconds = 3;
g_data_struct->func_ptr = timeout_cb;
// printf("=== timeout_cb: %p\n", timeout_cb);
start_stopwatch(g_data_struct);
// free(g_data_struct);
printf("=== End of Program - all threads in ===\n");
pthread_exit(NULL);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
stop_watch.h
/* stop_watch.h */
struct data_struct
{
int seconds;
void (*func_ptr)(void);
};
void start_stopwatch(struct data_struct *g_data_struct);
Run Code Online (Sandbox Code Playgroud)
stop_watch.c
#include <stdio.h>
#include <pthread.h>
#include "stop_watch.h"
static void* g_start_timer(void *args)
{
void (*function_pointer)();
int seconds = ((struct data_struct*) args)->seconds;
function_pointer = ((struct data_struct*) args)->func_ptr;
printf("=== go to sleep for %d\n", seconds);
sleep(seconds);
(void) (*function_pointer)();
pthread_exit(NULL);
return 0;
}
void start_stopwatch(struct data_struct *g_data_struct)
{
pthread_t thread_id;
int rc;
int seconds = g_data_struct->seconds;
printf("=== start_stopwatch(): %d\n", seconds);
rc = pthread_create(&thread_id, NULL, g_start_timer, (void *) &g_data_struct);
if(rc)
printf("=== Failed to create thread\n");
}
Run Code Online (Sandbox Code Playgroud)
该行start_stopwatch():
rc = pthread_create(&thread_id, NULL, g_start_timer, (void *) &g_data_struct);
Run Code Online (Sandbox Code Playgroud)
应该:
rc = pthread_create(&thread_id, NULL, g_start_timer, (void *) g_data_struct);
Run Code Online (Sandbox Code Playgroud)
在第一种情况下,当您真的只想将指针作为线程参数传递时,您将传递"指针指针".
至于何时释放数据,有很多选择.如果你总是在堆分配的块中传递线程数据,那么g_start_timer()线程proc可以在它完成拉出数据时释放它.请注意,如果执行此操作,则启动线程的部分协议是线程参数块必须是堆分配的.