美文网首页
linux线程创建

linux线程创建

作者: 嵌入式工作 | 来源:发表于2018-11-07 15:41 被阅读0次

1线程创建方法

pthread_create(&trd,NULL,creat1,(void*)b);
第二个参数为线程属性,通常为空
参数

第一个参数为指向线程标识符的指针。

第二个参数用来设置线程属性。

第三个参数是线程运行函数的地址。

最后一个参数是运行函数的参数。

注意

在编译时注意加上-lpthread参数,以调用静态链接库。因为pthread并非Linux系统的默认库

2编译运行结果,主线程main和线程pthread交替执行。也就是说是当我们创建了线程pthread之后,两个线程都在执行,证明创建成功

test@ubuntu:~/test$ gcc -o trd thread.c -l pthread
test@ubuntu:~/test$ ./trd 
creat thread 
temp->a= 4
 temp->s=**test msg**
creat ok 

3测试源码

#include<sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <pthread.h>
struct member
{
    int a;
    char *s;
};
void *creat1(void *arg)
{
struct member *temp;
temp=(struct member*)arg;
 sleep(5);
printf("temp->a= %d\n temp->s=%s\n",temp->a,temp->s);

return   (void*)0;
    
}
int main(int argc,char*argv[])
{
    pthread_t trd;
    int error;
    struct member *b;
    
    b= (struct member*)malloc(sizeof(struct member));
    b->a=4;
    b->s="**test msg**";
    
    printf("creat thread \n");
    error = pthread_create(&trd,NULL,creat1,(void*)b);
    if(error)
    {
        printf("pthread_creat fail \n");
        exit(-1);
    }
    sleep(10);
    printf("creat ok \n");
    return 0;
    
}


4.阻塞线程方法

pthread_join(trd,NULL);//等待trd线程结束

相关文章

  • Linux 线程

    Linux支持内核线程,用户进程以及LWP,Linux2.6之后支持线程组概念。 内核线程是内核创建的线程,处理内...

  • linux线程创建

    1线程创建方法 pthread_create(&trd,NULL,creat1,(void*)b);第二个参数为线...

  • Linux线程创建

    以前都是Windows编程,一直说看看Linux下的线程编程,有空了,回顾一下吧。 头文件 Linux下线程相关函...

  • 你知道Linux并发与同步嘛?

    典型的UNIX系统都支持一个进程创建多个线程(thread)。 Linux以进程为单位组织操作,Linux中的线程...

  • 关于linux线程创建与销毁

    linux本没有线程的概念,它本身是一个”多进程单线程”模型,所以linux线程的创建并不是天生的,它是用户级上的...

  • LINUX多线程pipeline架构的创建分析

    参考: LINUX多线程pipeline架构的创建分析铁匠Smith先生的专栏-CSDN博客 Linux操作系统进...

  • linux 线程

    Linux下的线程创建[https://blog.csdn.net/luke_sanjayzzzhong/arti...

  • Linux学习-进程管理与调度(二)-进程的创建与销毁

    一、进程与线程的创建 Linux创建进程方式:fork():以复制的方式创建子进程,然后直接把资源复制给新创建的进...

  • framework 学习笔记19. 知识点1(framework

    Linux 系统中,创建线程函数为:pthread_create();在 Android 中,通过调用 pthre...

  • iOS多线程

    1.Pthreads 真正跨平台的多线程技术,可以跨UNIX、Linux、windows平台。 创建Pthread...

网友评论

      本文标题:linux线程创建

      本文链接:https://www.haomeiwen.com/subject/feevxqtx.html