0
点赞
收藏
分享

微信扫一扫

线程相关函数讲解


      我们都知道,Linux 中的线程其实就是进程,只是线程共享进程的地址空间,其他的没有什么特别,线程也具有进程描述符,内核栈,thread_info 结构等等,进程所具有的东西。

      创建线程我们需要用到的函数是 pthread_create,线程和进程一样,需要进程进行等待,以释放线程占用的其他资源,哈哈,这又和进程的实现是一样的,主线程等待子线程的函数是 pthread_join,好吧,下面我们看一段代码吧。


/*
 * dlut_pthread.c
 *
 *  Created on: 2014年1月9日
 *      Author: DLUTBruceZhang
 */


#include <stdio.h>
#include <pthread.h>
#include <unistd.h>

#define THREAD_COUNT		2

void 		dlut_print_thread_id();
void * 	dlut_thread_func(void *arg);

int main(int argc, char **argv, char **environ)
{
	int i = 0;

	pthread_t tid[THREAD_COUNT];

	void *status;

	for (i = 0; i != THREAD_COUNT; i++)
	{
		pthread_create((pthread_t *)&tid[i], NULL, dlut_thread_func, (void *)"BruceZhang");
	}

	pthread_join(tid[0], &status);
	pthread_join(tid[1], &status);

	return 0;
}

void dlut_print_thread_id(char *s)
{
	pthread_t tid;

	tid = pthread_self();

	printf("%s : this new thread's id is %d\n", s, (int)tid);
	
	sleep(3);

	return;
}

void * dlut_thread_func(void *arg)
{
	dlut_print_thread_id((char *)arg);

	return (void *)0;
}



运行程序,我们发现,主线程需要等待三秒才结束,如果没有等待的话,那么进程会直接结束,不过,通常我们不这样做,我们一般不想等待子线程的话(因为这样会阻塞主线程),在web服务器中这一点相当重要,因为,主线程需要做一些其他的工作,这时,我们需要做的就是分离子线程,这时我们用到的函数是 pthread_detach,它的作用就是不用这个主线程去回收资源,而是子线程结束之后自行释放它的资源,下面我们来看下它的实现方法:


/*
 * dlut_pthread.c
 *
 *  Created on: 2014年1月9日
 *      Author: DLUTBruceZhang
 */


#include <stdio.h>
#include <pthread.h>
#include <unistd.h>

#define THREAD_COUNT		2

void 		dlut_print_thread_id();
void * 	dlut_thread_func(void *arg);

int main(int argc, char **argv, char **environ)
{
	int i = 0;

	pthread_t tid[THREAD_COUNT];

	void *status;

	for (i = 0; i != THREAD_COUNT; i++)
	{
		pthread_create((pthread_t *)&tid[i], NULL, dlut_thread_func, (void *)"BruceZhang");
	}

	for (i = 0; i != THREAD_COUNT; i++)
	{
		pthread_detach(tid[i]);
	}
	
	sleep(1);

	return 0;
}

void dlut_print_thread_id(char *s)
{
	pthread_t tid;

	tid = pthread_self();

	printf("%s : this new thread's id is %d\n", s, (int)tid);
	

	return;
}

void * dlut_thread_func(void *arg)
{
	dlut_print_thread_id((char *)arg);

	return (void *)0;
}



这时,就是分离的子线程自行工作,自行释放资源。

举报

相关推荐

0 条评论