C 为什么我的线程在第二次运行打印一行后停止?
我正在使用pthreads,并试图在主线程上运行无限循环。循环应该打印“Hello world!”10次,然后创建一个单独的线程来写“Hello moon!”10次,然后重新开始 出于某种原因,我的程序的输出(始终): 而不是永远奔跑 守则如下:C 为什么我的线程在第二次运行打印一行后停止?,c,pthreads,C,Pthreads,我正在使用pthreads,并试图在主线程上运行无限循环。循环应该打印“Hello world!”10次,然后创建一个单独的线程来写“Hello moon!”10次,然后重新开始 出于某种原因,我的程序的输出(始终): 而不是永远奔跑 守则如下: #include <stdio.h> #include <stdlib.h> #include <pthread.h> #include <unistd.h> #define SEC_IN_NSEC(x
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#define SEC_IN_NSEC(x) (x * 1000000000)
pthread_mutex_t mutex;
void *hello_moon(void *param);
int main(int argc, char **argv)
{
pthread_t moon_tid;
pthread_mutex_init(&mutex, NULL);
while(1) {
pthread_mutex_lock(&mutex);
for(int i = 0; i < 10; i++) {
printf("Hello world!\n");
sleep(1);
}
pthread_mutex_unlock(&mutex);
pthread_create(&moon_tid, NULL, hello_moon, NULL);
pthread_join(moon_tid, NULL);
}
pthread_mutex_destroy(&mutex);
}
void* hello_moon(void *param)
{
struct timespec ts;
ts.tv_nsec = SEC_IN_NSEC(0.2); // 0.2 s in ns
pthread_mutex_lock(&mutex);
for(int i = 0; i < 10; i++) {
printf("Hello moon!\n");
nanosleep(&ts, NULL);
}
pthread_mutex_unlock(&mutex);
pthread_exit(0);
}
#包括
#包括
#包括
#包括
#定义SEC(x)(x*100000000)
pthread_mutex_t mutex;
void*hello_moon(void*param);
int main(int argc,字符**argv)
{
pthread_t moon_tid;
pthread_mutex_init(&mutex,NULL);
而(1){
pthread_mutex_lock(&mutex);
对于(int i=0;i<10;i++){
printf(“你好,世界!\n”);
睡眠(1);
}
pthread_mutex_unlock(&mutex);
pthread_create(&moon_tid,NULL,hello_moon,NULL);
pthread_join(moon_tid,NULL);
}
pthread_mutex_destroy(&mutex);
}
void*hello_moon(void*param)
{
结构timespects;
ts.tv_nsec=SEC_IN_nsec(0.2);//0.2s IN ns
pthread_mutex_lock(&mutex);
对于(int i=0;i<10;i++){
printf(“你好,月亮!\n”);
奈米睡眠(&ts,空);
}
pthread_mutex_unlock(&mutex);
pthread_退出(0);
}
有人知道为什么会这样吗
更新:我注释掉了sleep和nanosleep调用并运行了它,然后它按预期循环。但是,我仍然希望打印之间有延迟。正如@KamilCuk在评论中指出的,您忘记初始化
tv_sec
成员:
struct timespec ts;
ts.tv_sec = 0; // add this, otherwise the member can be initialized with garbage
ts.tv_nsec = SEC_IN_NSEC(0.2); // 0.2 s in ns
此外,如果缺少标题,请在文件开头添加以下内容:
#define _POSIX_C_SOURCE 200809L
#include <time.h>
#定义POSIX_C_SOURCE200809L
#包括
struct timespec ts
那么,ts.tv\u sec
的价值是什么呢?我不是一个伟大的Linux专家,但在这里它陷入了nanosleep(&ts,NULL)代码>@KamilCuk哈,这很奇怪。我将它设置为0,现在它可以工作了。我认为它默认为0,因为之前我有一个非常不同的代码版本,它工作得非常好,而且我也没有指定ts.tv_sec。谢谢Protip:define如果用s+1
这样的表达式调用,将失败。更改为秒(x)((x)*100000000)
@LostMikely一般建议:避免使用宏。它们有时很有用,但很少。
#define _POSIX_C_SOURCE 200809L
#include <time.h>