转载_深入浅出剖析C语言函数指针与回调函数(三)

前面两篇文章:

http://blog.csdn.net/morixinguan/article/details/65494239

http://blog.csdn.net/morixinguan/article/details/65938128

 

在UNix多线程编程中,我们会使用到以下函数:

Pthread_create,

我们来看看它的原型:

 

int  pthread_create((pthread_t *thread,  pthread_attr_t  *attr,  void  *(*start_routine)(void *),  void  *arg)

参数说明:

(1)    thread:表示线程的标识符

(2)    attr:表示线程的属性设置

(3)    start_routine:表示线程函数的起始地址

(4)    arg:表示传递给线程函数的参数

函数的返回值为:

(1)    success:返回0

(2)    fair:返回-1

    看到这个函数的第三个参数,这不就是一个函数指针,同时也是一个回调函数嘛!这就是函数指针和回调函数在UNIX环境多线程编程中的应用。

我们在windows的dev C++上写一个测试程序来看看:

 

  1. #include <stdio.h>  
  2. #include <pthread.h>  
  3.   
  4.   
  5. void *function(void *args)  
  6. {  
  7.     while(1)  
  8.     {  
  9.         printf("hello world1!\n");  
  10.         sleep(1);  
  11.     }  
  12. }  
  13. int main(void)  
  14. {  
  15.     pthread_t tid ;  
  16.     tid = pthread_create(&tid , NULL , function , NULL);  
  17.     while(1)  
  18.     {  
  19.         printf("hello world!\n");  
  20.         sleep(1);  
  21.     }  
  22.     return 0 ;  
  23. }  
#include <stdio.h>
#include <pthread.h>


void *function(void *args)
{
	while(1)
	{
		printf("hello world1!\n");
		sleep(1);
	}
}
int main(void)
{
	pthread_t tid ;
	tid = pthread_create(&tid , NULL , function , NULL);
	while(1)
	{
		printf("hello world!\n");
		sleep(1);
	}
	return 0 ;
}
   运行结果:

 

 

    我们会看到在main函数里的打印语句和在线程回调函数里打印语句在同时打印。

关于这个函数的如何使用,网上文章有很多讲得非常的详细,这里仅仅只是写函数指针和回调函数的应用,详细可以参考这篇文章,了解进程和线程。

http://blog.csdn.net/tommy_wxie/article/details/8545253




posted @ 2017-12-14 14:11  大海中的一粒沙  阅读(187)  评论(0)    收藏  举报