#include <stdlib.h>
#include <stdio.h>
#include <signal.h>
#include <unistd.h>
#include <stdint.h>
#include <math.h>
#include <string.h>
#include <pthread.h>
void printtest(char *str)
{
printf("printtest str=%s\n", str);
}
void printtest2(char *str)
{
printf("printtest2 =%s\n", str);
}
struct printst
{
void (*print1)(char *str);
char *savestr;
};
void *threadloop( void *arg )
{
struct printst *printest = (struct printst *)arg;
while (1)
{
printest->print1(printest->savestr);
sleep(1);
}
}
int print_callback( void (*print1)(char *str), char *savestr )
{
/*/不能使用static和局部变量,否则函数运行结束数据释放 程序出错
需要在整个线程运行阶段进行malloc,确保数据一直有地方存放,
线程结束后才进行free
*/
struct printst *printest = malloc(sizeof(struct printst));
if(NULL == printest)
return -1;
printest->print1 = print1;
printest->savestr = savestr;
//printest.print1(printest.savestr);
pthread_t test1;
pthread_create(&test1, NULL, threadloop, printest );
//free(printest);//不能free,否则线程无法找到数据,段错误
}
int main(int argc, char *argv[])
{
char test[20]="have a good day";
print_callback( printtest2,test );
print_callback( printtest,test );
while(1)
{
sleep(1);
}
}
02-05