c - pthread_join 不起作用,互斥锁在 C 中不起作用
问题描述
由于代码几乎相同,我得到了两个相似的问题。我是使用线程的新手,但我对这个想法和概念并不陌生,但我无法让它发挥作用......
该任务,创建两个线程(加上主线程),一个以短延迟打印 hello moon 三次,另一个以长延迟打印 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
期望线程 id 而不是指向它的指针作为第一个参数。
pthread_join(&thread_id2, NULL);
pthread_join(&thread_id1, NULL);
应该
pthread_join(thread_id2, NULL);
pthread_join(thread_id1, NULL);
推荐阅读
- ios - 如何在 Realm 中通过 NSDate 属性正确查询对象?
- php - 从主 SQL 查询插入子查询计数
- django - 默认语言值覆盖管理员中的翻译字段
- mysql - 如何优化此选择位置和“日期时间”sql?
- sql-server - 就行存储数据页概念而言,聚集列存储索引和非聚集列存储索引有什么区别
- c++ - 实现 std::error_category,与自定义命名空间一起使用时的名称解析问题
- python - 使用 PIL 库获取“'NoneType' 对象没有属性 'items'”错误
- javascript - 从同一服务器获取数据。使用什么网址?
- angular - 拖动后点击事件触发
- apache-spark - Kafka 到 Spark 流使用 Pyspark 错误