我想知道使用POSIX调用pthread_once()和/ sem_wait()或dispatch_*函数会更好/更快,所以我创建了一个小测试并对结果感到惊讶(问题和结果在最后).
在测试代码中,我使用mach_absolute_time()来为调用计时.我真的不在乎这与纳秒没有完全匹配; 我正在将这些值相互比较,因此确切的时间单位无关紧要,只有间隔之间的差异.结果部分中的数字是可重复的而不是平均数; 我可以平均时间,但我不是在寻找确切的数字.
test.m(简单的控制台应用程序;易于编译):
#import <Foundation/Foundation.h>
#import <dispatch/dispatch.h>
#include <semaphore.h>
#include <pthread.h>
#include <time.h>
#include <mach/mach_time.h>
// *sigh* OSX does not have pthread_barrier (you can ignore the pthread_barrier
// code, the interesting stuff is lower)
typedef int pthread_barrierattr_t;
typedef struct
{
pthread_mutex_t mutex;
pthread_cond_t cond;
int count;
int tripCount;
} pthread_barrier_t;
int pthread_barrier_init(pthread_barrier_t *barrier, const pthread_barrierattr_t *attr, unsigned int count)
{
if(count == 0)
{
errno = EINVAL;
return -1;
}
if(pthread_mutex_init(&barrier->mutex, 0) < 0) …Run Code Online (Sandbox Code Playgroud) 我似乎无法让netbeans识别pthread_barrier_t类型.我可以输入#include<pthread.h>,但在pthread_barrier_t上没有运气.
以下是构建和错误:
g ++ -lpthread -c -g -MMD -MP -MF build/Debug/GNU-MacOSX/main.od -o build/Debug/GNU-MacOSX/main.o main.cpp main.cpp:32:错误:'pthread_barrier_t '没有说出一种类型
我正在使用Netbeans 7.1,我在Mac OSX 10.7.2上我可以创建没有任何编译问题的线程.
bool isNotInSteadyState()
{
int rc = 0;
threadData threadDataArray[NUM_THREADS];
int dataArrayCount = 0;
if (NUM_THREADS < ((PLATE_SIZE - 2) * (PLATE_SIZE - 2)))
{
for (int i = 1; i < PLATE_SIZE - 1; i += sqrt(NUM_THREADS))
{
for (int j = 1; j < PLATE_SIZE - 1; j += sqrt(NUM_THREADS))
{
threadDataArray[dataArrayCount].endY = i + sqrt(NUM_THREADS) - …Run Code Online (Sandbox Code Playgroud)