Linux系统编程--多线程基本操作(1)

声明

以下内容仅供学习,如有侵权,联系作者删除。
参考文献:B站up主:C语言技术网
链接: C语言技术网–Linux多线程
链接: C语言技术网

一 基本操作

1.创建线程

2.回收线程资源

3.终止线程

#include <pthread.h>
int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
                          void *(*start_routine) (void *), void *arg);  //创建线程
                          
int pthread_join(pthread_t thread, void **retval);  //等待线程结束
note:参数 thread,需要等待的线程 id。
	  参数 retval,输出参数,用于接收等待退出的线程的退出码(Exit Code),
	  线程退出码可以通过调用 pthread_exit 退出线程时指定,也可以在线程函数中通过 return 语句返回。 
void pthread_exit(void *retval);  // 终止线程
note:参数 retval 的值可以在 pthread_join 中拿到,没有可以设置为 NULL

二 示例

pthread_join 函数等待其他线程退出期间会挂起等待的线程,被挂起的线程不会消耗宝贵的CPU时间片。直到目标线程退出后,等待的线程会被唤醒。

/*
 *程序启动时,创建一个工作线程,工作线程将当前系统时间写入文件中后退出,
 *主线程等待工作线程退出后,从文件中读取出时间并显示在屏幕上。
 *作者:jack 日期:20210618
 *参考作者:C语言技术网(www.freecplus.net), B站UP主:C语言技术网
*/
#include <stdio.h>
#include <string.h>
#include <pthread.h>

#define MAXSIZE	50  // 存放时间字符串的长度

void *fileThreadFunc(void *arg);

int main()
{
 pthread_t ptimeid;  // 线程id

 // 创建一个线程
 if (pthread_create(&ptimeid, NULL, fileThreadFunc, NULL) != 0)
 {
     printf("创建线程失败,程序退出。\n");  return -1;
 }

 int *retval;
 printf("等待子线程退出。\n");
 pthread_join(ptimeid,(void **)&retval);
 printf("子线程已经退出。\n");

 
 FILE *fp = 0;
 if ( (fp = fopen("time.txt", "r")) == 0 )
 {
     printf("打开文件time.txt失败。\n");  return -1;
 }
 
 char buf[MAXSIZE];
 if ( fread(buf, 1, MAXSIZE, fp) == 0 )
 {
     printf("打开文件time.txt失败。\n");  return -1;
 }

 printf("当前时间为:%s\n",buf);
 return 0;
}


void *fileThreadFunc(void *arg)
{
 time_t tnow = time(0);	// 获取当前时间
 struct tm *sttm = localtime(&tnow);	// 把整数的时间转换为struct tm结构体的时间
 char strtime[MAXSIZE];
 snprintf(strtime, MAXSIZE, "%04u-%02u-%02u %02u:%02u:%02u\n", 
 		sttm->tm_year+1900,
 		sttm->tm_mon+1,
 		sttm->tm_mday,
 		sttm->tm_hour,
 		sttm->tm_min,
 		sttm->tm_sec);

 FILE *fp = 0;
 if ( (fp = fopen("time.txt", "w")) == 0 )
 {
     printf("打开文件time.txt失败。\n");  return;
 }

 fwrite(strtime, 1, strlen(strtime)+1, fp);

 fclose(fp);
}

运行结果如下:
在这里插入图片描述

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值