在C中,可以定义struct,typedefed,并声明为:
typedef struct {
int bar;
} Foo;
Foo foo;
Run Code Online (Sandbox Code Playgroud)
要么:
struct Foo {
int bar;
} foo;
typedef struct Foo Foo;
Run Code Online (Sandbox Code Playgroud)
我认为这有点不一致,而且过于冗长.我希望它能像C++一样工作.
在C++中,您不需要指定typedef struct Foo Foo;能够声明结构Foo foo;而不是struct Foo foo;.为什么没有将它引入C标准或作为编译器标志选项?是否有任何C代码的例子如果typedef struct在C中被选为可选的话会破坏?
我试图用pthread_cond_timedwait等待Java的超时等待wait(long timeout, int nanos).我知道Java wait使用相对超时,而pthread_cond_timedwait使用绝对时间阈值.尽管考虑到这一点,pthread_cond_timedwait似乎立即返回错误代码ETIMEDOUT.
下面的示例程序打印一个值<0.我希望它打印一个值> = 0.
我使用pthread_cond_timedwait不正确吗?如何重写以下程序以添加例如5秒的延迟?
#define _POSIX_C_SOURCE 199309L
#include <stdio.h>
#include <pthread.h>
#include <time.h>
#include <errno.h>
int main(void) {
pthread_mutex_t mutex;
pthread_cond_t cond;
pthread_mutex_init(&mutex, NULL);
pthread_cond_init(&cond, NULL);
pthread_mutex_lock(&mutex);
struct timespec t1;
struct timespec t2;
clock_gettime(CLOCK_MONOTONIC, &t1);
t1.tv_sec += 5;
while(pthread_cond_timedwait(&cond, &mutex, &t1) != ETIMEDOUT);
clock_gettime(CLOCK_MONOTONIC, &t2);
printf("%d", t2.tv_sec - t1.tv_sec);
pthread_mutex_unlock(&mutex);
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&cond);
return 0;
}
Run Code Online (Sandbox Code Playgroud)