线程的创建与使用

#include <string.h>
#include <stdlib.h>
#include <iostream>
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>

using namespace std;

void *thread_1(void *)
{
    int i = 0;
    for (i=0; i<5; i++)
    {
        printf("This is thread 1111 -----\n");
        if (i == 3)
        {
            printf("Thread_1 will exit !!\n");
            pthread_exit(0);
        }

    }
}

void *thread_2(void *)
{
    int i = 0;
    for (i=0; i<6; i++)
    {
        printf("This is thread 2222 -----\n");
        if (i == 3)
        {
            printf("Thread_2 will usleep() !!\n");
            usleep(200000);
            pthread_exit(0);
        }

    }
}
int main()
{
    pthread_t id_1 = 0, id_2 = 0;
    int ret;

    ret = pthread_create(&id_1, NULL, thread_1, NULL);

    printf("Thread 111 ret_1 is %d\n", ret);
    if (ret != 0)
    {
        printf("Thread 111 create error !!\n");
        return -1;
    }

    ret = pthread_create(&id_2, NULL, thread_2, NULL);

    printf("Thread 222 ret_2 is %d\n", ret);
    if (ret != 0)
    {
        printf("Thread 222 create error !!\n");
        return -1;
    }

    pthread_join(id_1, NULL);
    pthread_join(id_2, NULL);

    return 0;
}

/** 线程创建问题,create一个线程后,并不一定马上执行,需要等当前主线程的时间片结束后,随机分配给
/*  下一个线程,所以没有特定的执行顺序,pthread_join为了保证所有线程执行结束,才结束主线程*/


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值