一个多线程绑定到不同cpu上的例子

01 #include
02 #include
03 #include
04 #include
05 #include
06 #include
07 #include
08 #include
09  
10 #define INC_TO 1000000 // one million...
11  
12 int global_int = 0;
13  
14 pid_t gettid( void )
15 {
16     return syscall( __NR_gettid );
17 }
18  
19 void *thread_routine( void *arg )
20 {
21     int i;
22     int proc_num = (int)(long)arg;
23     cpu_set_t set;
24  
25     CPU_ZERO( &set );
26     CPU_SET( proc_num, &set );
27  
28     if (sched_setaffinity( gettid(), sizeof( cpu_set_t ), &set ))
29     {
30         perror"sched_setaffinity" );
31         return NULL;
32     }
33  
34     for (i = 0; i < INC_TO; i++)
35     {
36 //      global_int++;
37         __sync_fetch_and_add( &global_int, 1 );
38     }
39  
40     return NULL;
41 }
42  
43 int main()
44 {
45     int procs = 0;
46     int i;
47     pthread_t *thrs;
48  
49     // Getting number of CPUs
50     procs = (int)sysconf( _SC_NPROCESSORS_ONLN );
51     if (procs < 0)
52     {
53         perror"sysconf" );
54         return -1;
55     }
56  
57     thrs = mallocsizeof( pthread_t ) * procs );
58     if (thrs == NULL)
59     {
60         perror"malloc" );
61         return -1;
62     }
63  
64     printf"Starting %d threads...\n", procs );
65  
66     for (i = 0; i < procs; i++)
67     {
68         if (pthread_create( &thrs[i], NULL, thread_routine,
69             (void *)(long)i ))
70         {
71             perror"pthread_create" );
72             procs = i;
73             break;
74         }
75     }
76  
77     for (i = 0; i < procs; i++)
78         pthread_join( thrs[i], NULL );
79  
80     free( thrs );
81  
82     printf"After doing all the math, global_int value is: %d\n",
83         global_int );

你可能感兴趣的:(Linux)