首页 > 编程语言 > 详细

C - pthread多线程最简单示例

时间:2015-12-17 22:34:53      阅读:410      评论:0      收藏:0      [点我收藏+]
#include <pthread.h>
#include <stdio.h>

/* this function is run by the first thread */
void *inc_x(void *x_void_ptr)
{
    printf("线程XXXXXXXXXXXXXXXXXXXXXXX开始\n");
    /* increment x to 100 */
    int *x_ptr = (int *)x_void_ptr;
    while(++(*x_ptr) < 100){
        printf("线程X: %d\n", *x_ptr);
    }
    printf("线程XXXXXXXXXXXXXXXXXXXXXXX结束\n");
    /* the function must return something - NULL will do */
    return NULL;
}

/* this function is run by the second thread */
void *inc_y(void *y_void_ptr)
{
    printf("线程YYYYYYYYYYYYYYYYYYYYYY开始\n");
    /* increment x to 100 */
    int *y_ptr = (int *)y_void_ptr;
    while(++(*y_ptr) < 100){
        printf("线程Y: %d\n", *y_ptr);
    }
    printf("线程YYYYYYYYYYYYYYYYYYYYYY结束\n");
    /* the function must return something - NULL will do */
    return NULL;
}

int main()
{
    int x = 0, y = 0;

    /* show the initial values of x and y */
    printf("x: %d, y: %d\n", x, y);

    /* this variable is our reference to the first thread */
    pthread_t inc_x_thread;
    /* this variable is our reference to the second thread */
    pthread_t inc_y_thread;

    /* create a first thread which executes inc_x(&x) */
    if(pthread_create(&inc_x_thread, NULL, inc_x, &x)) {
        fprintf(stderr, "Error creating thread\n");
        return 1;
    }

    /* create a second thread which executes inc_x(&x) */
    if(pthread_create(&inc_y_thread, NULL, inc_y, &y)) {
        fprintf(stderr, "Error creating thread\n");
        return 1;
    }

    /* wait for the second thread to finish */
    if(pthread_join(inc_x_thread, NULL)) {
        fprintf(stderr, "Error joining thread\n");
        return 2;
    }

    if(pthread_join(inc_y_thread, NULL)) {
        fprintf(stderr, "Error joining thread\n");
        return 2;
    }

    /* show the results - x is now 100 thanks to the second thread */
    printf("x: %d, y: %d\n", x, y);

    return 0;
}


C - pthread多线程最简单示例

原文:http://2241728500.blog.51cto.com/10783688/1725821

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!