我正在尝试编写一个涉及线程的C程序。用户输入一个数字,并创建一个线程来计算该数字的正弦值。现在,当我编译并运行代码时,线程似乎永远不会终止。我还在源代码的注释中包括了用于编译该程序的步骤。
#include <stdio.h>
#include <math.h>
#include <pthread.h>
/*
compile:
1. gcc MyName.c -o MyName -lm -lpthread
2. ./MyName.c
*/
double result;
double x;
void *calcSin(void *u);
int main()
{
pthread_t tid;
pthread_attr_t attr;
pthread_attr_init(&attr); //Set thread attributes
pthread_create(&tid, &attr, calcSin, NULL); //Create thread
pthread_join(tid,NULL); //Wait until new thread completes
printf("First thread completed here is sin: %lf\n", result);
return 0;
}
void *calcSin(void *u)
{
result = 0;
printf("Enter first number: \n");
scanf("%lf\n",&x);
result = sin(x);
pthread_exit(0);
}
只需从scanf中删除'\ n',它就可以工作。scanf自动执行。