/*thread.c*/
#include <stdio.h>
#include <pthread.h>
/*线程一*/
void thread_1(void)
{
int i;
for(i=0; i<10; i++) {
printf("This is a pthread_1.\n");
sleep(1);
}
pthread_exit(0);
}
/*线程二*/
void thread_2(void)
{
int i;
for(i=0; i<5; i++) {
printf("This is a pthread_2.\n");
sleep(1);
}
pthread_exit(0);
}
int main(void)
{
pthread_t id_1,id_2;
int i,ret;
/*创建线程一*/
ret = pthread_create(&id_1, NULL, (void *)thread_1, NULL);
if(ret != 0)
{
printf("Create pthread error!\n");
return -1;
}
/*创建线程二*/
ret = pthread_create(&id_2, NULL, (void *)thread_2, NULL);
if(ret != 0)
{
printf("Create pthread error!\n");
return -1;
}
/*等待线程结束*/
pthread_join(id_1, NULL);
pthread_join(id_2, NULL);
return 0;
}
//gcc pthread.c -lpthread
int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
void *(*start_routine) (void *), void *arg);
pthread_t *thread指向线程标识符的指针。
pthread_attr_t *attr 设置的
线程属性。
void *(*start_routine) (void *)
线程运行函数的起始地址。
void *arg
运行函数的参数。
返回值
若线程创建成功,则返回0。若线程创建失败,则返回出错编号,并且*thread中的内容是未定义的。
返回成功时,由tidp指向的内存单元被设置为新创建线程的线程ID。attr参数用于指定各种不同的线程属性。新创建的线程从start_rtn函数的地址开始运行,该函数只有一个万能指针参数arg,如果需要向start_rtn函数传递的参数不止一个,那么需要把这些参数放到一个结构中,然后把这个结构的地址作为arg的参数传入。
linux下用C语言开发多线程程序,Linux系统下的多线程遵循POSIX线程接口,称为pthread。
注意事项:
因为pthread并非Linux系统的默认库,而是POSIX线程库。在Linux中将其作为一个库来使用,因此加上 -lpthread(或-pthread)以显式链接该库。函数在执行错误时的错误信息将作为返回值返回,并不修改系统全局变量errno,当然也无法使用perror()打印错误信息。
头文件 : #include <pthread.h>
函数定义: int
pthread_join(pthread_t thread, void **retval);
描述 :
pthread_join()函数,以阻塞的方式等待thread指定的线程结束。当函数返回时,被等待线程的资源被收回。如果进程已经结束,那么该函数会立即返回。并且thread指定的线程必须是joinable的。
参数 :
thread: 线程
标识符,即线程ID,标识唯一线程。
retval: 用户定义的指针,用来存储被等待线程的返回值。
返回值 : 0代表成功。 失败,返回的则是错误号。
void pthread_exit(void* retval);
线程通过调用pthread_exit函数终止执行,就如同进程在结束时调用exit函数一样。
这个函数的作用是,终止调用它的线程并返回一个指向某个对象的指针。
本文详细介绍了C语言中使用pthread库进行多线程编程的方法,包括线程的创建、运行、等待线程结束以及线程退出机制。通过实例展示了如何在Linux环境下创建和管理两个线程,实现并发操作。
1011

被折叠的 条评论
为什么被折叠?



