Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/63.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/linux/27.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 尝试使用用户使用线程输入的数字来计算sin函数_C_Linux_Multithreading_Pthreads_Math.h - Fatal编程技术网

C 尝试使用用户使用线程输入的数字来计算sin函数

C 尝试使用用户使用线程输入的数字来计算sin函数,c,linux,multithreading,pthreads,math.h,C,Linux,Multithreading,Pthreads,Math.h,我正在尝试编写一个包含线程的C程序。用户输入一个数字,并创建一个线程来计算该数字的sin值。现在,当我编译并运行代码时,线程似乎永远不会终止。我还在源代码的注释中包含了编译这个程序的步骤 #include <stdio.h> #include <math.h> #include <pthread.h> /* compile: 1. gcc MyName.c -o MyName -lm -lpthread 2. ./MyName.c */ double re

我正在尝试编写一个包含线程的C程序。用户输入一个数字,并创建一个线程来计算该数字的sin值。现在,当我编译并运行代码时,线程似乎永远不会终止。我还在源代码的注释中包含了编译这个程序的步骤

#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);
}


#包括
#包括
#包括
/*
汇编:
1.gcc MyName.c-o MyName-lm-lpthread
2. ./我的名字
*/
双重结果;
双x;
void*calcSin(void*u);
int main()
{
pthread_t tid;
pthread_attr_t attr;
pthread_attr_init(&attr);//设置线程属性
pthread_create(&tid,&attr,calcSin,NULL);//创建线程
pthread_join(tid,NULL);//等待新线程完成
printf(“这里完成的第一个线程是sin:%lf\n”,结果);
返回0;
}
void*calcSin(void*u)
{
结果=0;
printf(“输入第一个数字:\n”);
scanf(“%lf\n”和&x);
结果=sin(x);
pthread_退出(0);
}

只要从scanf中删除“\n”,它就可以工作了。
scanf会自动执行此操作。

您是否测试过,如果您不使用线程直接调用
calcSin
,此代码是否有效?仅供参考,在任何有意义的多线程程序中,在启动新线程之后和加入新线程之前,您都会让主线程执行其他操作。如果主线程不与新线程同时执行任何操作,那么它实际上只是编写单线程程序的一个稍微慢一点、更复杂的等效程序。如何将math.h和pthread.h库编译在一起?可以将库与程序动态链接。使用-lm和-lpthread标志(lion中为-l,Iron中为-I)。附带说明:math.h和pthread.h不是库本身,只是它们的头文件,当您动态链接库时,实际上是告诉链接器在其路径中查找您希望使用的库,方法是添加-lmy_lib,链接器将搜索库名称libmy_lib.so。这里的库是libmath.So和libpthread.So。