前言
最近在看OSTEP,这里主要写一些阅读时遇到的问题与解决办法
第二章
2.1展示了这样一段代码 首先sys/time.h头文件显示了这是个运行在Linux上的代码,然后我把这段代码CV过去,一编译,缺少头文件= =,然后又是Spin函数未定义,查了下资料,原来是我不知道看漏了哪里,这里应该有个common.h的!!!代码如下:
#ifndef __common_h__
#define __common_h__
#include <sys/time.h>
#include <assert.h>
#include <pthread.h>
double
GetTime()
{
struct timeval t;
int rc = gettimeofday(&t, NULL);
assert(rc == 0);
return (double)t.tv_sec + (double)t.tv_usec/1e6;
}
void
Spin(int howlong)
{
double t = GetTime();
while((GetTime() - t) < (double)howlong)
;
}
void
Pthread_create(pthread_t *t, const pthread_attr_t *attr,
void *(*start_routine)(void *), void* arg) {
int rc = pthread_create(t, attr, start_routine, arg);
assert(rc == 0);
}
void
Pthread_join(pthread_t thread, void **value_ptr) {
int rc = pthread_join(thread, value_ptr);
assert(rc == 0);
}
void
Pthread_mutex_lock(pthread_mutex_t *mutex) {
int rc = pthread_mutex_lock(mutex);
assert(rc == 0);
}
void
Pthread_mutex_unlock(pthread_mutex_t *mutex) {
int rc = pthread_mutex_unlock(mutex);
assert(rc == 0);
}
void
Pthread_mutex_init(pthread_mutex_t *mutex, pthread_mutexattr_t *attr) {
int rc = pthread_mutex_init(mutex, attr);
assert(rc == 0);
}
#endif
我粘贴进去之后再编译,发现报了这个错:
/usr/bin/ld: /tmp/ccjTj0Sq.o: in function Pthread_create': cpu.c:(.text+0x101): undefined reference to pthread_create’ /usr/bin/ld: /tmp/ccjTj0Sq.o: in function Pthread_join': cpu.c:(.text+0x153): undefined reference to pthread_join’ collect2: error: ld returned 1 exit status
再查了一下资料后发现原来需要给编译选项加一个-pthread 这下编译通过了: 同时如预期运行了: 紧接着我把中文版的图2.2的命令
敲了进去,发现:
bash: 未预期的符号“;”附近有语法错误
然后我顺便看了一下原文: 哪来的分号啊淦,我就说这个linux如此奇怪! 改成./cpu A & ./cpu B & ./cpu C & ./cpu D & 后顺利运行:
|