21xrx.com
2024-09-20 00:07:05 Friday
登录
文章检索 我的文章 写文章
C++ 如何启动线程:代码示例
2023-07-05 09:33:43 深夜i     --     --
C++ 启动线程 代码示例

C++是一种被广泛应用的编程语言,支持多线程编程。在多线程编程中,启动线程是一个非常重要的操作。本文将介绍C++如何启动线程的方法,提供一些代码示例供参考。

1. 使用std::thread

C++11引入了std::thread类,它是一个提供了线程管理的库。有了std::thread,启动线程变得非常简单。

示例代码:


#include <iostream>

#include <thread>

void thread_func()

{

  std::cout << "Hello from thread!\n";

}

int main()

{

  std::thread t(thread_func);

  t.join();

  return 0;

}

这段代码中,我们定义了一个函数thread_func(),它将被作为新线程的入口点。在main()函数中,我们实例化了一个std::thread对象t,并将其初始化为thread_func()函数的执行结果。最后,我们调用t.join()来等待新线程执行完毕。

2. 使用C函数pthread_create

除了std::thread之外,C++还支持使用C函数pthread_create()来启动线程。虽然这种方法相对于std::thread而言更为底层,但在某些情况下仍然非常有用。

示例代码:


#include <iostream>

#include <pthread.h>

void* thread_func(void* arg)

{

  std::cout << "Hello from thread!\n";

  pthread_exit(NULL);

}

int main()

{

  pthread_t thread;

  pthread_create(&thread, NULL, thread_func, NULL);

  pthread_join(thread, NULL);

  return 0;

}

在这个例子中,我们定义了一个函数thread_func(),和使用std::thread时一样,它将作为新线程的入口点。使用pthread_create()创建线程时,我们需要传递四个参数:线程ID、线程属性、入口函数和入口函数的参数。最后,我们调用pthread_join()来等待新线程执行完毕。

总结

无论是使用std::thread还是C函数pthread_create,启动线程都是非常重要的。在选择使用哪种方法时,应根据具体情况进行选择。使用std::thread是更为推荐的方法,它提供了更高层次的抽象和更直观的代码。而使用C函数pthread_create,则适用于一些需要更为底层控制的场景。

  
  
下一篇: 编程入门指南

评论区

{{item['qq_nickname']}}
()
回复
回复