Learn gcc atomic variable#define _gnu_source#include <stdio.h> #include <stdlib.h> #include <unistd.h > #include <pthread.h> #include <sys/syscall.h> #include <linux/unistd.h> #include <errno.h > #include <sched.h> #define INC_TO 1000000//Every thread adds 1 million timesint global_int = 0;//Get current T Hread idpid_t Gettid (void) {return syscall (__nr_gettid); return pthread_self (); Cannot work ...} void *thread_routine (void *arg) {int i; int proc_num = (int) (long) (ARG); cpu_set_t set; A CPU Affinity Mask Cpu_zero (&set); Cpu_set (Proc_num, &set); ETS the CPU affinity mask of this thread to the value specified by Maski. A thread ' s CPU affinity mask determines the set of CPUs on which it's eligible to run. if (Sched_setaffinity (Gettid (), sizeof (cpu_set_t), &set)) {perror ("sched_setaffinity"); return NULL; } for (i = 0; i < inc_to; i++) {//global_int + +; __sYnc_fetch_and_add (&global_int, 1); } return NULL; int main () {int procs = 0; int i; pthread_t *threads; Get the number of processors currently online (available). procs = (int) sysconf (_SC_NPROCESSORS_ONLN); Mine is + if (Procs < 0) {perror ("sysconf"); return-1; } threads = malloc (sizeof (pthread_t) * procs); if (threads = = NULL) {perror ("malloc threads"); return-1; } printf ("Set up%d threads ... \ n", procs); for (i = 0; i < procs; i++) {if (Pthread_create (&threads[i], NULL, Thread_routine, (void *) (long) i)) { Perror ("Pthread_create"); procs = i; Break }} for (i = 0; i < procs; i++) {Pthread_join (threads[i], NULL); } free (threads); printf ("All Threads-Done.global_int is%d\n", global_int); printf ("The expected value is%d\n", inc_to * procs); return 0;}
Reference: Http://www.alexonlinux.com/multithreaded-simple-data-type-access-and-atomic-variables
To bind a CPU to a thread