传递参数给线程

在demo1的基础上,添加了传递参数给线程。这样可以更明显地看到,进程依次创建了线程,但是线程的执行顺序却是不固定的。

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

void *fn(void *arg)
{
	printf("thread #%u : get arg=<%d>, my PID=%d\n", \
			(unsigned int)pthread_self(), (int)arg, getpid());
	return NULL;
}

int main(int argc, char *argv[])
{
	pthread_t tid;
	int error;
	int i;

	for(i=0; i<10; i++)
	{
		error = pthread_create( &tid, NULL, fn, (void*)i);
		if(0 != error)
		{
			perror("pthead_create error");
			return -1;
		}
		else
		{
			printf("main: my PID=%d, set arg=<%d>, create thread #%u OK!\n", \
					getpid(), i, (unsigned int)tid);
		}
	}

	sleep(3); /* give threads time to print out */
	return 0;
}


附执行结果:

main: my PID=3379, set arg=<0>, create thread #3075865408 OK!
main: my PID=3379, set arg=<1>, create thread #3067472704 OK!
main: my PID=3379, set arg=<2>, create thread #3059080000 OK!
main: my PID=3379, set arg=<3>, create thread #3050687296 OK!
main: my PID=3379, set arg=<4>, create thread #3042294592 OK!
main: my PID=3379, set arg=<5>, create thread #3033901888 OK!
main: my PID=3379, set arg=<6>, create thread #3025509184 OK!
main: my PID=3379, set arg=<7>, create thread #3017116480 OK!
main: my PID=3379, set arg=<8>, create thread #3008723776 OK!
main: my PID=3379, set arg=<9>, create thread #3000331072 OK!
thread #3025509184 : get arg=<6>, my PID=3379
thread #3033901888 : get arg=<5>, my PID=3379
thread #3042294592 : get arg=<4>, my PID=3379
thread #3017116480 : get arg=<7>, my PID=3379
thread #3050687296 : get arg=<3>, my PID=3379
thread #3008723776 : get arg=<8>, my PID=3379
thread #3059080000 : get arg=<2>, my PID=3379
thread #3000331072 : get arg=<9>, my PID=3379
thread #3075865408 : get arg=<0>, my PID=3379
thread #3067472704 : get arg=<1>, my PID=3379

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

yilonglucky

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值