首页 > 解决方案 > 如何在 C 中使用线程显示并行性?

问题描述

我正在学习在 C 中使用线程,我想制作一个可以同时做两件事的程序,我认为这就是并行性的定义。所以我用这段代码创建线程:

   pthread_t threads[NUM_THREADS];
   int rc, rc_2;
   int i;
   for( i = 0; i < NUM_THREADS; i++ ) {
      printf("main() : creating thread, %d\n", i);
      rc = pthread_create(&threads[i], NULL, PrintHello, (void *)i);
      rc_2 = pthread_create(&threads[i], NULL, PrintHello_2, (void *)i);
      if (rc || rc_2) {
         printf("Error:unable to create thread, %d\n", rc);
         exit(-1);
      }
   }

这些线程中的每一个都调用以下函数之一:

void *PrintHello(void *threadid) {
   long tid;
   tid = (long)threadid;
   printf("Hello World! Thread ID, %d\n", tid);
   printf("Valores a: %d, b: %d\n", a,b);
   a += 5;
   pthread_exit(NULL);
}

void *PrintHello_2(void *threadid) {
   long tid;
   tid = (long)threadid;
   printf("Hello World! Thread ID, %d\n", tid);
   printf("Valores a: %d, b: %d\n", a,b);
   b += 3;
   pthread_exit(NULL);
}

我有 2 个全局变量 a、b,我只是将它们添加 5 和 3 以显示它们是如何变化的。但问题是我不明白这是否是并行性..如果不是,我怎么能看到这两个函数或操作同时执行它们的代码?因为当我打印 a 和 b 值时,它看起来就像一个普通程序。

标签: cmultithreadingparallel-processingpthreads

解决方案


main()在线程有机会运行任意时间之前退出。 pthread_join()将等待线程退出main()。另一个问题是您的线程不是特别长时间运行。我通过运行一个长循环来解决这个问题。还修复了 int 被传递给线程但读取很长的问题。

#include <limits.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#define NUM_THREADS 2

void *PrintHello(void *threadid) {
    int tid = *(int *) threadid;
    for(int i = 0; i < INT_MAX; i += tid + 1) {
        printf("%d %d\n", tid, i);
    }
    pthread_exit(NULL);
}

int main() {
    pthread_t threads[NUM_THREADS];
    int ids[NUM_THREADS];
    for(int i = 0; i < NUM_THREADS; i++ ) {
        ids[i] = i;
        printf("main() : creating thread, %d\n", i);
        int rc = pthread_create(&threads[i], NULL, PrintHello, &ids[i]);
        if (rc) {
            printf("Error:unable to create thread, %d\n", rc);
            exit(-1);
        }
    }
    for(int i = 0; i < NUM_THREADS; i++ ) {
        pthread_join(threads[i], 0);
    }
}

这将打印如下内容:

1 166
0 265
0 266
1 168
0 267
1 170
1 172
1 174
1 176
1 178
0 268

输出流必须有一个互斥体,否则两个线程会产生混乱的输出。


推荐阅读