【发布时间】:2016-01-28 13:14:07
【问题描述】:
我目前是一名初学者,正在学习如何在 C 中使用 pthreads。我的代码目前正在运行,因此没有实际的错误,但它并没有达到预期的效果。该代码应提示用户提出每个问题,然后在用户输入其信息后打印所有结果,但一旦输入名称,该代码似乎会跳过并完成。请有人能帮我找到我的代码哪里出错了吗?以下是我的代码和运行时的输出:
#include <stdio.h
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
#include <sched.h>
#include <unistd.h>
#include <signal.h>
#include <sys/types.h>
#include <string.h>
#include <pthread.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
typedef struct compound {
char name [1024];
int age;
int birthMonth;
int birthYear;
int threadNumber;
}compound;
void * threadName (void * param){
compound *lparam = (compound *) param;
int lock;
lock = pthread_mutex_lock(&mutex);
printf ("> Please type your name for thread %d\n", lparam->threadNumber);
scanf ("%c", lparam->name);
lock = pthread_mutex_unlock(&mutex);
lock = pthread_mutex_lock(&mutex);
printf ("> Please type your age for thread %d\n", lparam->threadNumber);
scanf ("%d", &(lparam->age));
lock = pthread_mutex_unlock(&mutex);
lock = pthread_mutex_lock(&mutex);
printf ("> Please type your birth month for thread %d\n", lparam->threadNumber);
scanf ("%d", &(lparam->birthMonth));
lock = pthread_mutex_unlock(&mutex);
lock = pthread_mutex_lock(&mutex);
printf ("> Please type your birth year for thread %d\n", lparam->threadNumber);
scanf ("%d", &(lparam->birthYear));
lock = pthread_mutex_unlock(&mutex);
return NULL;
}
// main function
int main ( void) {
pthread_t thread_ID3, thread_ID4;
void *exitstatus;
compound first, second;
first.threadNumber= 1;
second.threadNumber = 2;
pthread_create (&thread_ID3, NULL, threadName, &first);
pthread_create (&thread_ID4, NULL, threadName, &second);
pthread_join (thread_ID3, &exitstatus);
pthread_join (thread_ID4, &exitstatus);
printf("Finished\n");
getchar();
return 0;
}
This is what happens when the code is executed:
[370user14@nostromo ex2]$ make
gcc -Wall -c base_code.c
gcc -lm -lpthread base_code.o -o baseprog
rm -f *.o *~
[370user14@nostromo ex2]$ ./baseprog
> Please type your name for thread 1
gurinder
> Please type your age for thread 1
> Please type your birth month for thread 1
> Please type your name for thread 2
> Please type your age for thread 2
> Please type your birth month for thread 2
> Please type your birth year for thread 2
> Please type your birth year for thread 1
Finished
【问题讨论】:
-
“我的代码目前正在运行,所以没有实际的错误,但它不是它应该做的。”如果有错误,大多数游戏都会运行。错误是语义上的错误行为,它很好地允许代码编译。
-
您可能想在尝试多线程编程之前学习顺序编程。您对
scanf()的使用令人不安。 -
您可能想检查对
scanf的第一次调用,这似乎不符合读取字符串的正确格式... -
“我的代码目前正在运行,所以没有实际的错误,但它不是它应该做的事情”——这就是罗马人所说的“矛盾本身”的意思。
-
1) 发布的代码包含这一行:
#include <stdio.h缺少最终的>2) 发布的代码设置变量lock,但从未使用它。
标签: c macos terminal pthreads mutex