Commit 938ff79a by Ian Lance Taylor

runtime: use sched_getaffinity for runtime.NumCPU() on Linux

        Fixes Go issue 3921 for gccgo.

From Shenghou Ma.

From-SVN: r190282
parent 0d8e4dac
...@@ -2,46 +2,35 @@ ...@@ -2,46 +2,35 @@
// Use of this source code is governed by a BSD-style // Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
#include <string.h> #include <features.h>
#include <sys/types.h> #include <sched.h>
#include <fcntl.h>
#include <unistd.h>
#include "runtime.h" // CPU_COUNT is only provided by glibc 2.6 or higher
#include "defs.h" #if !defined(__GLIBC_PREREQ) || !__GLIBC_PREREQ(2, 6)
#define CPU_COUNT(set) _CPU_COUNT((unsigned int *)(set), sizeof(*(set))/sizeof(unsigned int))
static int _CPU_COUNT(unsigned int *set, size_t len) {
int cnt;
#ifndef O_CLOEXEC cnt = 0;
#define O_CLOEXEC 0 while (len--)
cnt += __builtin_popcount(*set++);
return cnt;
}
#endif #endif
#include "runtime.h"
#include "defs.h"
int32 int32
getproccount(void) getproccount(void)
{ {
int32 fd, rd, cnt, cpustrlen; cpu_set_t set;
const char *cpustr; int32 r, cnt;
const byte *pos;
byte *bufpos;
byte buf[256];
fd = open("/proc/stat", O_RDONLY|O_CLOEXEC, 0);
if(fd == -1)
return 1;
cnt = 0; cnt = 0;
bufpos = buf; r = sched_getaffinity(0, sizeof(set), &set);
cpustr = "\ncpu"; if(r == 0)
cpustrlen = strlen(cpustr); cnt += CPU_COUNT(&set);
for(;;) {
rd = read(fd, bufpos, sizeof(buf)-cpustrlen);
if(rd == -1)
break;
bufpos[rd] = 0;
for(pos=buf; (pos=(const byte*)strstr((const char*)pos, cpustr)) != nil; cnt++, pos++) {
}
if(rd < cpustrlen)
break;
memmove(buf, bufpos+rd-cpustrlen+1, cpustrlen-1);
bufpos = buf+cpustrlen-1;
}
close(fd);
return cnt ? cnt : 1; return cnt ? cnt : 1;
} }
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment