线程编程(笔记)

相关函数:

pthread_create函数:

 int pthread_create(pthread_t *tid, const pthread_attr_t *attr,
                          void *(*start_routine) (void *), void *arg);返回:若成功返回0,若出错返回正的Exxx值。

    thread:一个进程内的各个线程是由线程ID标识的,这些线程的数据类型为pthread_t。如果新的线程创建成功,它的ID就通过tid指针返回。

    attr:每个线程有多个属性:优先级、初始栈大小、是否应该是一个守护进程,等等。当创建线程时,我们可通过初始化一个pthread_attr_t变量来指定这些属性以覆盖默认值。我们通常采用默认值,这种情况下,我们只需把attr参数指定为一个空指针。

    最后创建一个线程时,我们应该指定一个它将执行的函数,称为它的线程启动函数。这个线程以调用该函数开始,以后或者显示地终止(调用pthread_exit)或隐式地终止(让该函数返回)。该函数的地址作为func参数指定,该函数唯一的调用参数则是一个指针arg。如果需要给该函数传递多个参数,我们就得把它们打包成一个结构,然后将地址作为这个唯一的参数,传递给线程启动函数。

    Pthread函数的返回值有两种:成功时返回0,出错时返回非零。与出错时返回-1,并置errno为某个正值的大多是系统函数不同,Pthread函数的返回值是正值的出错提示。  

pthread_join函数:

  int pthread_join(pthread_t thread, void **retval);

    我们可以调用pthread_join等待一个线程终止。类似于进程的waitpid。

pthread_self函数:

  pthread_t pthread_self(void);

    每个线程都有在某个给定的进程内标识自身的一个ID。这个线程ID有pthread_create函数返回,一个线程使用pthread_self取得自己的线程ID。

pthread_detach函数:

int pthread_detach(pthread_t thread);

    线程或者是可汇合的,或者是可脱离的。当可汇合的线程终止时,其线程ID和退出状态将保留,直到另外一个线程调用pthread_join。脱离的线程则像守护进程:当它终止时,所有资源都将释放,因此我们不能等待它终止。如果一个线程需要另一个线程的终止时间,那就最好保留第二个线程的可汇合性。

  pthread_detach函数将指定的线程变为脱离的。

pthread_exit函数:

  void pthread_exit(void *retval);

    终止一个线程的方法之一是调用pthread_exit。

测试代码:

#include <unistd.h>
#include <sys/types.h>
#include <pthread.h>

#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>

#define ERR_EXIT(m)			\
	do				\
	{				\
		perror(m);		\
		exit(EXIT_FAILURE);     \
	}while(0);			\

//线程入口函数
void* thread_routine(void *arg)
{
	int i;
	for(i=0; i<20; i++)
	{
		printf("B");
		fflush(stdout);
		usleep(20);
		if(i == 3)
			pthread_exit("ABC");
	}

	return 0;
}

int main(void)
{
	pthread_t tid;
	int ret;
	int i;
	//线程的错误处理
	if ((ret = pthread_create(&tid, NULL, thread_routine, NULL)) != 0)
	{
		fprintf(stderr, "pthread_create:%s\n",strerror(ret));
		exit(EXIT_FAILURE);
	}
	for(i=0; i<20; i++)
	{
		printf("A");
		fflush(stdout);
		usleep(20);

	}
	void *value;
	//等待新线程结束
	if((ret =pthread_join(tid, &value)) != 0)
	{
		fprintf(stderr, "pthread_create:%s\n",strerror(ret));
		exit(EXIT_FAILURE);
	}
	printf("\n");
	printf("return msg = %s\n",(char*)value);
	return 0;
}
注:参考UNIX网络编程卷2:进程间通信

猜你喜欢

转载自blog.csdn.net/qq_34938530/article/details/80149077