pthread_create示例
时间: 2023-07-07 10:43:19 浏览: 41
下面是一个简单的pthread_create示例,它创建了一个新线程,该线程会输出一条消息并退出:
```c
#include <stdio.h>
#include <pthread.h>
void *thread_func(void *arg) {
printf("Hello from thread!\n");
pthread_exit(NULL);
}
int main() {
pthread_t tid;
int ret = pthread_create(&tid, NULL, thread_func, NULL);
if (ret != 0) {
printf("Failed to create thread\n");
return 1;
}
printf("Hello from main thread!\n");
pthread_join(tid, NULL);
return 0;
}
```
这个程序会输出两条消息,一条来自主线程,另一条来自新线程。主线程在创建新线程后会立即输出消息,而新线程在启动后会输出自己的消息并退出。最后,主线程会等待新线程结束后再退出。
相关问题
pthread_create pthread_detach
这两个函数都是 POSIX 线程库中的函数,用于创建和分离线程。
`pthread_create` 函数用于创建一个新的线程。它接收四个参数:指向线程标识符的指针、线程属性、线程函数的地址以及传递给线程函数的参数。通过调用该函数,可以创建新的线程并开始执行指定的线程函数。
示例代码:
```c
#include <pthread.h>
void* thread_function(void* arg) {
// 线程函数的逻辑
return NULL;
}
int main() {
pthread_t thread;
int result = pthread_create(&thread, NULL, thread_function, NULL);
if (result != 0) {
// 线程创建失败的处理逻辑
}
// 主线程的逻辑
return 0;
}
```
`pthread_detach` 函数用于将一个线程设置为分离状态。分离状态的线程结束后会自动释放资源,无需由其他线程调用 `pthread_join` 函数来等待其结束。通常情况下,只有当线程不需要返回结果时才会将其设置为分离状态。
示例代码:
```c
#include <pthread.h>
void* thread_function(void* arg) {
// 线程函数的逻辑
return NULL;
}
int main() {
pthread_t thread;
int result = pthread_create(&thread, NULL, thread_function, NULL);
if (result != 0) {
// 线程创建失败的处理逻辑
}
result = pthread_detach(thread);
if (result != 0) {
// 线程分离失败的处理逻辑
}
// 主线程的逻辑
return 0;
}
```
希望能对你有所帮助!如果还有其他问题,请继续提问。
C++ pthread_create
pthread_create是C++中用于创建线程的函数。它是POSIX线程库的一部分,用于在多线程环境下创建新的线程。
pthread_create函数的原型如下:
```c++
int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine) (void *), void *arg);
```
参数说明:
- thread:指向pthread_t类型的指针,用于存储新创建线程的标识符。
- attr:指向pthread_attr_t类型的指针,用于设置线程的属性。可以传入NULL,表示使用默认属性。
- start_routine:指向函数指针,该函数是新线程要执行的函数。函数的返回类型必须为void*,参数类型为void*。
- arg:传递给start_routine函数的参数。
调用pthread_create函数后,会创建一个新的线程,并开始执行start_routine函数。start_routine函数可以是全局函数、静态成员函数或Lambda表达式等。
以下是一个简单的示例代码:
```c++
#include <iostream>
#include <pthread.h>
void* threadFunc(void* arg) {
int* num = static_cast<int*>(arg);
std::cout << "Thread number: " << *num << std::endl;
pthread_exit(NULL);
}
int main() {
pthread_t thread;
int num = 10;
int ret = pthread_create(&thread, NULL, threadFunc, &num);
if (ret != 0) {
std::cerr << "Failed to create thread" << std::endl;
return 1;
}
pthread_join(thread, NULL);
return 0;
}
```