【问题标题】:Printing out even and odd numbers using thread in C使用C中的线程打印出偶数和奇数
【发布时间】:2017-06-01 17:17:24
【问题描述】:
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <stdlib.h>

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void* thread_even(void* arg);
void* thread_odd(void* arg);

int main(int argc, char** argv) {

    pthread_t tid[2];

    pthread_create(&tid[0], 0, &thread_even, 0);
    pthread_create(&tid[1], 0, &thread_odd, 0);

    pthread_join(tid[0], NULL);
    pthread_join(tid[1], NULL);

    return 0;
}

void* thread_even(void* arg) {
    int* thread_id = (int*)arg;

    pthread_mutex_lock(&mutex);

    for(int i = 1; i <= *thread_id; i++)
    {
        if(i%2 != 0)
        {
            printf("Thread 1: %d", i);
        }
    }

    pthread_mutex_unlock(&mutex);

    return NULL;
}

void* thread_odd(void* arg) {
    int* thread_id = (int*)arg;

    pthread_mutex_lock(&mutex);

    for(int i = 1; i <= *thread_id; i++)
    {
        if(i%2 == 0)
        {
            printf("Thread 2: %d", i);
        }
    }

    pthread_mutex_unlock(&mutex);

    return NULL;
}

上面是我正在处理的代码,但是我得到一个段错误错误......我想要实现的是,例如,

当我编译它并使用参数 8 (./number 8) 运行时

应该打印出来

线程 1:1

线程 2:2

线程 1:3

...等到数字8。

其中线程1代表偶数,线程2代表奇数。

请帮助...我想发展我的 C 知识,但没有人可以问.. 谢谢。

【问题讨论】:

  • int* thread_id = (int*)arg; - 嗯...你将NULL 作为pthread_create 的参数传递给arg 在这里。毫不奇怪,i &lt;= *thread_id 取消引用 NULL,从而调用 未定义的行为
  • 那么我应该传递什么作为参数以使程序成功?谢谢!
  • @seung,看我的回答。此外,您所做的锁定可能比您正在寻找的更粗糙。正如您现在所拥有的那样,实际上一个线程将完成,然后另一个线程将运行。
  • @EvanTeran 我真的很抱歉,但我真的很想知道如何以我的方式做到这一点......我能知道我应该将什么参数传递给偶数和奇数函数吗?
  • 这个“交替运行线程代码”问题有数百个重复项。当两个信号量是理智的解决方案时,他们似乎都尝试使用互斥锁(如果任何此类要求是理智的 - 这显然是一项练习/家庭作业)。为什么他们都尝试使用错误的同步?是因为 'mutex' 是一个更酷的名字,还是需要更少的输入?

标签: c pthreads computer-science


【解决方案1】:

看起来您正在将0 AKA NULL 传递给pthread_create 的最后一个参数,然后执行以下操作:

int* thread_id = (int*)arg;
pthread_mutex_lock(&mutex);
for(int i = 1; i <= *thread_id; i++)

所以,thread_id 肯定是 NULL,引用它将是一个 SEGFAULT。

如果你想为每个线程传递一个上限,你可以这样做:

int main(int argc, char** argv) {

    pthread_t tid[2];
    int *ids = malloc(2 * sizeof(int));
    ids[0] = 10; /* upper bound for thread 1 */
    ids[1] = 10; /* upper bound for thread 2 */

    pthread_create(&tid[0], 0, &thread_even, &ids[0]);
    pthread_create(&tid[1], 0, &thread_odd, &ids[1]);

    pthread_join(tid[0], NULL);
    pthread_join(tid[1], NULL);

    free(ids);
    return 0;
}

有一些方法可以在不使用堆分配的情况下做到这一点,但这是最直接的。

【讨论】:

  • 非常感谢!但它会像这样打印出线程 1 线程 1 和线程 2 线程 2。有什么办法可以打印出来吗?
  • 正如我的评论所提到的,您编写的互斥锁将在一个线程中完成。如何解决这个问题是一个单独的问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-08-26
  • 1970-01-01
  • 1970-01-01
  • 2013-05-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多