第一个LINUX多线程程序

本文通过一个简单的C语言示例介绍了多线程编程的基本概念。示例中创建了一个独立的线程,该线程重复打印消息,展示了线程如何并发执行任务。此程序有助于理解线程的基本工作原理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我对什么是线程的概念目前还并不是很清楚,只是按照书上的实例先学写一个多线程程序,让自己有一个线程编程的意思:

 

//////////////////////////////////////////////////////source code/////////////////////////////////////////////////

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

void *thread_function(void *ar)
{
int i;
for(i=0;i<20;i++)
 {
   printf("this is a thread!/n");
 }
 return NULL;
}
int main(void)
{
 pthread_t mythread;
 if(pthread_create(&mythread,NULL,thread_function,NULL))
{
 printf("error creating thread./n");
 abort();
}

"mypthread_test.c" 33 lines, 473 characters
//////////////////////////////////////////////////////end///////////////////////////////////////////////////////

 

////////////////////////////////////////////debug///////////////////////////////////////////

fei@fei-pc:~$ vi mypthread_test.c
fei@fei-pc:~$ gcc -lpthread -o mypthread_test mypthread_test.c
fei@fei-pc:~$ ./mypthread_test
This is main process!
this is a thread!
this is a thread!
this is a thread!
this is a thread!
this is a thread!
this is a thread!
this is a thread!
this is a thread!
this is a thread!
this is a thread!
this is a thread!
this is a thread!
this is a thread!
this is a thread!
this is a thread!
this is a thread!
this is a thread!
this is a thread!
this is a thread!
this is a thread!
fei@fei-pc:~$
/////////////////////////////////////////////////////////////////////////////

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值