我正在尝试编译以下C代码:
// (c) Partha Dasgupta 2009
// permission to use and distribute granted.
#define _GNU_SOURCE
//#define _POSIX_C_SOURCE 200809L
//#define _XOPEN_SOURCE 700
#include <stdio.h>
#include <stdlib.h>
#include "threads.h"
#include <unistd.h>
typedef pthread_mutex_t lock_t;
lock_t L1;
void init_lock(lock_t *l)
{
pthread_mutex_init(l, NULL);
}
void lock(lock_t *l)
{
pthread_mutex_lock (l);
}
void unlock (lock_t *l)
{
pthread_mutex_unlock (l);
pthread_yield();
}
void function_1(void)
{
while (1){
lock(&L1);
printf("Beginning of CS: func 1\n");
sleep(1);
printf("End of CCS: func 1..\n");
sleep(1);
unlock(&L1);
}
}
void function_2(void)
{
while (1){
lock(&L1);
printf("Beginning of CS: func 2\n");
sleep(1);
printf("End of CCS: func 2..\n");
sleep(1);
unlock(&L1);
}
}
void function_3(void)
{
while (1){
lock(&L1);
printf("Beginning of CS: func 3\n");
sleep(1);
printf("End of CCS: func 3..\n");
sleep(1);
unlock(&L1);
}
}
int main()
{
init_lock(&L1);
start_thread(function_1, NULL);
start_thread(function_2, NULL);
start_thread(function_3, NULL);
while(1) sleep(1);
return 0;
}
threads.h文件包含以下代码:
// (c) Partha Dasgupta 2009
// permission to use and distribute granted.
#include <pthread.h>
pthread_t start_thread(void *func, int *arg)
{
pthread_t thread_id;
int rc;
printf("In main: creating thread\n");
rc = pthread_create(&thread_id, NULL, func, arg);
if (rc){
printf("ERROR; return code from pthread_create() is %d\n", rc);
exit(-1);
}
return(thread_id);
}
我正在使用OS X终端中的以下内容进行编译:
gcc -lpthread lock_test.c
我得到的错误信息是:
lock_test.c:29:5: warning: implicit declaration of function 'pthread_yield' is invalid in C99 [-Wimplicit-function-declaration]
pthread_yield();
^
1 warning generated.
Undefined symbols for architecture x86_64:
"_pthread_yield", referenced from:
_unlock in lock_test-ed5a79.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
我无法理解为什么我无法编译它。 它在Linux机器上运行得非常好,但在OS X中却不行。
我应该怎样做才能编译?