Linux 创建线程thread

创建线程,并等待线程执行完成,回收线程的资源

void* thread_fun(void *arg)
{
	printf("thread_fun start\n");
    int i;
    for (i = 0; i < 3; ++i) {
        printf("I am %lx ------ %d\n", pthread_self(), i);
        usleep(1000);
    }
	printf("thread_fun end\n");
}

int main() {
	pthread_t thread;
	int ret = pthread_create(&thread, NULL, thread_fun, NULL);
	printf("mpthread_join...\n");
    //等待线程执行完成
	pthread_join(thread, NULL);
	printf("pthread_join end\n");
    return 0;
}

编译

gcc main.c -lpthread -o thread

执行结果

由于pthread库不是Linux系统默认的库,连接时需要使用库libpthread.a,所以在使用pthread_create创建线程时,在编译中要加-lpthread参数:
gcc -o pthread -lpthread pthread.c

如果还不对,很有可能是-lpthread放置的位置不对:

gcc pthread.c -lpthread -o pthread

设置线程分离

线程分离状态:指定该状态,线程主动与主控线程断开关系。使用pthread_exit或者线程自动结束后,其退出状态不由其他线程获取,而直接自己自动释放。网络、多线程服务器常用。

在线程thread_fun中设置线程分离

void* thread_fun(void *arg)
{
	 //设置线程为分离属性
	pthread_detach(pthread_self());
	printf("thread_fun start\n");
    int i;
    for (i = 0; i < 3; ++i) {
        printf("I am %lx -- %d\n", pthread_self(), i);
        usleep(1000);
    }
	printf("thread_fun end\n");
}

int main() {
	
	pthread_t thread;
	int ret = pthread_create(&thread, NULL, thread_fun, NULL);
	printf("mpthread_join...\n");
	 //子线程设置分离属性,则pthread_join不再阻塞,立刻返回
	ret=pthread_join(thread, NULL);
	if(ret!=0)
		printf("pthread_join error \n");
	printf("pthread_join end\n");
    return 0;
}

执行结果如下

创建线程的时候通过属性设置线程分离

void* thread_fun(void *arg)
{
	printf("thread_fun start\n");
    int i;
    for (i = 0; i < 3; ++i) {
        printf("I am %lx -- %d\n", pthread_self(), i);
        usleep(1000);
    }
	printf("thread_fun end\n");
}

int main() {
	
	//定义pthread_attr_t类型的变量
	pthread_attr_t attr;

	//初始化attr变量
	pthread_attr_init(&attr);

	//设置attr为分离属性
	pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);

	//创建子线程
	pthread_t thread;
	int ret = pthread_create(&thread, &attr, thread_fun, NULL);
	
	//释放线程属性
    pthread_attr_destroy(&attr);
		
	printf("mpthread_join...\n");
	 //子线程设置分离属性,则pthread_join不再阻塞,立刻返回
	ret=pthread_join(thread, NULL);
	if(ret!=0)
		printf("pthread_join error \n");
	printf("pthread_join end\n");
    return 0;
}

执行结果如下

创建线程之后设置线程分离

void* thread_fun(void *arg)
{

	printf("thread_fun start\n");
    int i;
    for (i = 0; i < 3; ++i) {
        printf("I am %lx -- %d\n", pthread_self(), i);
        usleep(1000);
    }
	printf("thread_fun end\n");
}

int main() {
	
	pthread_t thread;
	int ret = pthread_create(&thread, NULL, thread_fun, NULL);
	//设置线程为分离属性
	pthread_detach(thread);
	printf("mpthread_join...\n");
	 //子线程设置分离属性,则pthread_join不再阻塞,立刻返回
	ret=pthread_join(thread, NULL);
	if(ret!=0)
		printf("pthread_join error \n");
	printf("pthread_join end\n");
    return 0;
}

执行结果如下

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值