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