【发布时间】:2020-01-27 16:00:51
【问题描述】:
由于代码几乎相同,我得到了两个相似的问题。我是使用线程的新手,但我对这个想法和概念并不陌生,但我无法让它发挥作用......
任务,创建两个线程(加上主线程),一个以短延迟打印 hello moon 3 次,另一个以长延迟打印 hello world 3 次,一个接一个。
代码的第一个版本有一个问题,即即使我使用连接,main 有时也会在线程完成其工作之前退出。这是代码:
更新:使用 pthread_join(&....);这不是一个好主意。我应该使用 pthread_join(...); (没有&)这部分似乎现在可以正常工作。
#include <stdio.h>
#include <stdlib.h>
#include "wrapper.h"
#include <pthread.h>
#include <sys/time.h>
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void *HelloMoon (void * arg){
pthread_mutex_lock(&mutex);
struct timeval stop, start;
int i = 0;
gettimeofday(&start, NULL);
while(i < 3){
gettimeofday(&stop, NULL);
if((stop.tv_usec-start.tv_usec)>=20000){
printf("Hello Moon!\n");
gettimeofday(&start, NULL);
i++;
}
}
pthread_mutex_unlock(&mutex);
return NULL;
}
void *printHelloWorld(void* arg){
pthread_mutex_lock(&mutex);
struct timeval stop, start;
int i = 0;
gettimeofday(&start, NULL);
while(i < 3){
gettimeofday(&stop, NULL);
if((stop.tv_sec-start.tv_sec)>=1){
printf("Hello world!\n");
gettimeofday(&start, NULL);
i++;
}
}
pthread_mutex_unlock(&mutex);
return(NULL);
}
int main(int ac, char * argv)
{
pthread_t thread_id1, thread_id2;
pthread_create(&thread_id2, NULL, HelloMoon, NULL);
pthread_create(&thread_id1, NULL, printHelloWorld, NULL);
pthread_join(&thread_id2, NULL);
pthread_join(&thread_id1, NULL);
return(0);
}
第二个代码在 main 中使用了一个 while 循环来使行为永远重复。这“解决”了 main 退出的问题,但有时一个线程运行两次,使其打印 6 次而不是 3 次。这是为什么?代码:
更新:我认为这是因为循环每次运行时都会创建两个新线程,使线程总数大于两个,反过来,具有相同 ID 的多个线程会导致这种有趣的行为。我说的对吗?
int main(int ac, char * argv)
{
pthread_t thread_id1, thread_id2;
while(1==1){
pthread_create(&thread_id2, NULL, HelloMoon, NULL);
pthread_create(&thread_id1, NULL, printHelloWorld, NULL);
pthread_join(&thread_id2, NULL);
pthread_join(&thread_id1, NULL);
}
return(0);
}
最后一个问题,让线程一个接一个地永远运行的最好方法是什么? while 循环是个好主意吗?线程的变量“i”是否相同?我认为不是,但一位消息人士说是这样,所以我想确定一下。
【问题讨论】:
-
一,启用所有编译器警告 - 你应该会看到一些东西。第二,您没有检查任何返回值。这些在这里是相关的......
-
"使线程总数大于两个,而这反过来," 不,因为对
pthread_join()的调用注意在迭代期间创建的两个线程都是消失了,在下一次迭代开始之前。 -
wrapper.h中有什么内容? -
wrapper.h 暂时为空,未使用
-
检查您使用的任何可能以这种方式发出错误信号的函数的返回值是一个好习惯。
标签: c multithreading pthreads