Linux多线程编程-线程创建

要求

编程实现在主进程中通过线程创建pthread_create()函数来创建新的线程。
在主线程和子线程中要通过getpid()及pthread _self()获取对应的进程号和线程号并打印输出

实现代码

#include
#include
#include
#include

void* func(void *arg) {
     
    printf("Thread created successfully\n");
    printf("Thread id is %ld\n", (unsigned long)pthread_self());
    return 0;
}

int main(int argc, char const *argv[])
{
     
    pthread_t threadId;
    int ret = pthread_create(&threadId, NULL, func, NULL);
    if(ret == -1) {
     
        printf("Thread create error!\n");
        exit(1);
    }
    //sleep(1); //增加此语句就会让主进程陷入阻塞,从而使子线程能够充分执行
    printf("Parent begin\n");
    printf("Parent id is %d\n", getpid());
    sleep(1); //避免主进程结束后子线程未执行完就退出
}

pthread_creat()

  • 功能:创建一个新的线程
  • 函数声明:
    int pthread_create( pthread_t pthread,
    const pthread_attr_t
    attr,
    void*(start_routine)(void),
    void *arg)
  • 头文件:#include
  • 参数说明:
    • thread:返回线程ID,此参数是一个输出型参数 (返回的是新创建的线程的ID)

    • attr:设置线程的属性,attr为NULL表示使用默认属性(一般设为NULL)
      (设置的是新线程的属性)

    • start_routine:是个函数地址,线程启动后需要执行的函数(这是一个函数指针,指向线程的入口函数)

    • arg:传给线程启动函数的参数

  • 返回值:成功返回0,失败返回-1

注意:编译时要连接库libpthread;就是编译的时候要加 -lpthread或-pthread。

pthread_self()

  • 功能:返回当前线程的ID
  • 函数声明:pthread_self(void)
  • 头文件: #include
  • 参数:无
  • 返回值:返回线程的ID

运行结果

编译并执行上述代码,运行结果如下:
在这里插入图片描述
“printf("Parent begin\n");”前加sleep(1);使主进程陷入阻塞,先执行子线程作为参数的函数中的语句,在执行主进程中的语句。
在这里插入图片描述

最后

  • 由于博主水平有限,难免有疏漏之处,欢迎读者批评指正!

你可能感兴趣的:(Linux,多线程,linux,并发编程)