SHOGUN
v3.2.0
|
00001 /* 00002 * This program is free software; you can redistribute it and/or modify 00003 * it under the terms of the GNU General Public License as published by 00004 * the Free Software Foundation; either version 3 of the License, or 00005 * (at your option) any later version. 00006 * 00007 * Written (W) 1999-2009 Soeren Sonnenburg 00008 * Copyright (C) 1999-2009 Fraunhofer Institute FIRST and Max-Planck-Society 00009 */ 00010 00011 #include <shogun/base/Parallel.h> 00012 #include <shogun/lib/RefCount.h> 00013 00014 #if defined(LINUX) && defined(_SC_NPROCESSORS_ONLN) 00015 #include <unistd.h> 00016 #elif defined(DARWIN) 00017 #include <sys/types.h> 00018 #include <sys/sysctl.h> 00019 #endif 00020 00021 00022 using namespace shogun; 00023 00024 Parallel::Parallel() 00025 { 00026 num_threads=get_num_cpus(); 00027 m_refcount = new RefCount(); 00028 } 00029 00030 Parallel::Parallel(const Parallel& orig) 00031 { 00032 num_threads=orig.get_num_threads(); 00033 m_refcount = new RefCount(orig.m_refcount->ref_count()); 00034 } 00035 00036 Parallel::~Parallel() 00037 { 00038 delete m_refcount; 00039 } 00040 00041 int32_t Parallel::get_num_cpus() const 00042 { 00043 #if defined(LINUX) && defined(_SC_NPROCESSORS_ONLN) 00044 return sysconf( _SC_NPROCESSORS_ONLN ); 00045 #elif defined(DARWIN) 00046 int num; /* for calling external lib */ 00047 size_t size=sizeof(num); 00048 if (!sysctlbyname("hw.ncpu", &num, &size, NULL, 0)) 00049 return num; 00050 #endif 00051 return 1; 00052 } 00053 00054 void Parallel::set_num_threads(int32_t n) 00055 { 00056 #ifndef HAVE_PTHREAD 00057 ASSERT(n==1) 00058 #endif 00059 num_threads=n; 00060 } 00061 00062 int32_t Parallel::get_num_threads() const 00063 { 00064 return num_threads; 00065 } 00066 00067 int32_t Parallel::ref() 00068 { 00069 return m_refcount->ref(); 00070 } 00071 00072 int32_t Parallel::ref_count() const 00073 { 00074 return m_refcount->ref_count(); 00075 } 00076 00077 int32_t Parallel::unref() 00078 { 00079 int32_t rc = m_refcount->unref(); 00080 00081 if (rc==0) 00082 { 00083 delete this; 00084 return 0; 00085 } 00086 00087 return rc; 00088 }