#include <pthread.h> (1)int pthread_create(pthread_t *thread,pthread_attr_t *attr,void *(*start_routine)(void *),void *arg); pthread_t pthread_self(void); (2)int pthread_equal(pthread_t thread1,pthread_t thread2); (3)int pthread_once(pthread_once_t *once_control,void(*init_routine)(void));
1.线程创建: int pthread_create(pthread_t thread,pthread_attr_t *attr,void (start_routine)(void ),void *arg); pthread_t pthread_self(void); 参数说明: thread:指向pthread_create类型的指针,用于引用新创建的线程。 attr:用于设置线程的属性,一般不需要特殊的属性,所以可以简单地设置为NULL。 (start_routine)(void ):传递新线程所要执行的函数地址。 arg:新线程所要执行的函数的参数。 调用如果成功,则返回值是0,如果失败则返回错误代码。 2.线程终止 void pthread_exit(void *retval); 参数说明: retval:返回指针,指向线程向要返回的某个对象。 线程通过调用pthread_exit函数终止执行,并返回一个指向某对象的指针。注意:绝不能用它返回一个指向局部变量的指针,因为线程调用该函数后,这个局部变量就不存在了,这将引起严重的程序漏洞。 3.线程同步 int pthread_join(pthread_t th, void **thread_return); 参数说明: th:将要等待的线程,线程通过pthread_create返回的标识符来指定。 thread_return:一个指针,指向另一个指针,而后者指向线程的返回值。
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void *thread_function(void *arg);
char message[] = "Hello World";
int main()
{
int res;
pthread_t a_thread;
void *thread_result;
res = pthread_create(&a_thread, NULL, thread_function, (void *)message);
if (res != 0)
{
perror("Thread creation failed!");
exit(EXIT_FAILURE);
}
printf("Waiting for thread to finish.../n");
res = pthread_join(a_thread, &thread_result);
if (res != 0)
{
perror("Thread join failed!/n");
exit(EXIT_FAILURE);
}
printf("Thread joined, it returned %s/n", (char *)thread_result);
printf("Message is now %s/n", message);
exit(EXIT_FAILURE);
}
void *thread_function(void *arg)
{
printf("thread_function is running. Argument was %s/n", (char *)arg);
sleep(3);
strcpy(message, "Bye!");
pthread_exit("Thank you for your CPU time!");
}
$./thread1[输出]: thread_function is running. Argument was Hello World Waiting for thread to finish... Thread joined, it returned Thank you for your CPU time! Message is now Bye!
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有