模拟智能家居项目Part10

来自于两周的粤嵌实习,主要是网络编程和线程控制部分比较重要,贯穿了常用的C语言用法,值得做一个复盘,共有11个部分,本节介绍了线程的使用。

Posted by LJJ on July 3, 2020

模拟智能家居项目

基本原理

  • 线程 线程就是并发 为了提高cpu的利用率,提高实际问题当中的效率 也为了实现并发,所以我们要使用线程 线程是操作系统任务调度的最小单位

  • 如何创建线程

    通过这个创建线程的API接口函数创建pthread_create()

    1.头文件
    #include <pthread.h>
    2.函数的功能 
    创建一个子线程
    3.函数的原型
    int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
    void *(*start_routine) (void *), void *arg);
    4.函数的参数
    pthread_t *thread				//填pthread_t的一个指针,
    为了保存线程创建成功以后的一个线程ID	
    const pthread_attr_t *attr		//设置这个线程的属性,一般填NULL,采用默认属性
      
    void *(*start_routine) (void *) //函数指针,指向一个返回值类型是void * ,然后接收
    void*的参数的这样的一个函数
      
    void *arg						//填你要传到这个函数指针指向的这个函数里面去的参数
    如果你不要传参 就填个NULL
      
    5.函数的返回值
    成功:返回0
    失败:线程ID号不会被设置
      
    注意:在代码中使用了创建线程的API函数 那么我们在编译的时候 要在编译命令行后面加一个 -lpthread
    如 gcc test.c  -lpthread
    

任务要求

  • 写一个简单的程序使用创建线程的接口
  • 创建一个子线程 然后编译 运行一下

代码实现

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

void *test(void *ar)
{
	while(1)
	{
		printf("this  is  son  thread\n");
		sleep(3);
	}
}


int main()
{
	printf("hello\n");
	
	pthread_t id;
	
	int n = pthread_create(&id, NULL,test, NULL);
	if(n != 0)
	{
		perror("create thread fail\n");
		return -1;
	}
	long int *p = (long int *)&id;
	printf("id is %ld\n",*p);
	while(1)
	{
		printf("this is main thread\n");
		sleep(3);
	}
	
	return 0;
}