多线程(零):入门——一个最简单的多线程程序

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

void thread(void) {
	int i;
	printf("This is a thread.\n");
	pthread_exit(NULL);
}

int main(void) {
	pthread_t id;
	int ret;
	ret = pthread_create(&id, NULL, (void *)thread, NULL);
	if(ret != 0) {
		printf("Create pthread error!\n");
		exit(1);
	}
	int i;
	printf("This is the main process.\n");
	pthread_join(id, NULL);
	return 0;
}

函数说明:

int pthread_create(pthread_t*restrict tidp,const pthread_attr_t *restrict_attr,void*(*start_rtn)(void*),void *restrict arg);

此函数接受四个参数,分别为指向线程标识符的指针、线程属性、线程运行函数的起始地址、运行函数的参数。第二个和第四个参数暂时都为NULL,以后也许会修改。

若此函数执行成功,则返回0,否则返回错误编号。

pthread_t用于声明线程id。

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

此函数以阻塞的方式等待thread指定的线程结束。当函数返回时,被等待线程的资源被收回。如果进程已经结束,那么该函数会立即返回。在这里的意思是主函数在等待线程都结束后才退出,如果不加这个函数的话,主函数执行完自己的代码程序就终止了,不在乎线程是否也执行结束。

第一个参数为线程ID,标识唯一线程。第二个参数为用户定义的指针,用来存储被等待线程的返回值。

若此函数执行成功,则返回0。否则返回错误编号。


注:编译时要加上-lpthread,如果允许使用gdb调试的话,还要加上-g

gcc -o homework1 homework1.c -lpthread

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值