线程创建以及运行
#include <pthread.h>
/* 创建子线程
* 函数名: pthread_create
* 参数:
* thread 保存新创建线程ID的变量地址值。线程与进程相同,也需要用于区分线程的ID。
* attr 用于传递线程属性的参数,传递NULL时,创建默认属性的线程。
* atart_routine 子线程开始执行的函数地址值。
* arg 传递线程调用函数时的包含参数信息的变量地址值
* 返回值: 0成功,非0不成功
*/
int pthread_create(pthread_t *restrict thread,
const pthread_attr_t *restrict attr,
void *(* start_routine)(void *),
void *restrict arg);
/* 销毁子线程(调用该函数的进程或者线程将进入等待状态,直到第一个参数ID的线程终止为止)
* 函数名: pthread_join
* 参数:
* thread 该参数值ID的线程终止后才会从该函数返回
* status 保存线程的main函数返回值(返回值的指针变量值)
*/
int pthread_join(pthread_t thread, void ** status);
// 例子
// 子线程执行的函数
void* thread_main(void* arg)
{
int count = *(int*)arg;
char* msg = (char*)malloc(sizeof(char) * 50);
strcpy(msg, "Hello,I'am thread~");
for (int index = 0; index < count; ++index)
{
sleep(1);
puts("running thread");
}
return (void*)msg;
}
int main(int argh,const char* argv[])
{
pthread_t t_id;
int pthread_param = 5;
if(pthread_create(&t_id,NULL,thread_main,&pthread_param) != 0)
{
puts("pthread_create() error");
}
void* thread_result = NULL;
if(pthread_join(t_id,&thread_result) != 0)
{
puts("pthread_join() error");
}
printf("Thread return message : %s\n",(char*)thread_result);
free(thread_result);
puts("end of main");
return 0;
}