多线程

线程创建以及运行

#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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值