多线程测试

截图

代码

#include <stdio.h>
#include <pthread.h>
#include <time.h>
void *Thread1(void *arg)
{
    printf("线程1:");
    srand((unsigned int)time(NULL));
    int n = 0;
    int A[10] = {-1};
    int Temp = -1;
    while (n<10)
    {
        Temp= rand()%100;
        if(Temp%2 == 0)
        {
            A[n] = Temp;
        }
        else
        {
            A[n] = Temp +1;
        }    
        n++;
    }
    for(int i=0;i<10;i++)
    {
        printf("%d ",A[i]);
    }
    printf("\n");
    return "Thread1成功执行";
}

void* Thread2(void* arg)
{
    printf("线程2:");
    srand((unsigned int)time(NULL));
    int n = 0;
    int A[10] = {-1};
    int Temp = -1;
    while (n<10)
    {
        Temp= rand()%100;
        if(Temp%2 == 1)
        {
            A[n] = Temp;
        }
        else
        {
            A[n] = Temp +1;
        }    
        n++;
    }
    for(int i=0;i<10;i++)
    {
        printf("%d ",A[i]);
    }
    printf("\n");
    return "Thread1成功执行";
}

int main()
{
    int res;
    pthread_t mythread1, mythread2;
    void* thread_result;
    
    res = pthread_create(&mythread1, NULL, Thread1, NULL);
    if (res != 0) {
        printf("线程创建失败");
        return 0;
    }

    res = pthread_create(&mythread2, NULL, Thread2, NULL);
    if (res != 0) {
        printf("线程创建失败");
        return 0;
    }
 
    res = pthread_join(mythread1, &thread_result);

    printf("%s\n", (char*)thread_result);
   
    res = pthread_join(mythread2, &thread_result);
    printf("%s\n", (char*)thread_result);
    printf("主线程执行完毕\n");
    return 0;
}

posted @ 2022-11-10 09:00  戴骏  阅读(26)  评论(0编辑  收藏  举报