线程绑定

#include<unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include<pthread.h>
#include <sched.h>

#include<iostream>

using namespace std;

typedef struct {
  pthread_spinlock_t spinlock;
  int count;
}ThdArgs ;

void * thd_func(void *arg){
 
  while(true){
    pthread_spinlock_t *spinlock = (pthread_spinlock_t*)arg;
    pthread_spin_lock(spinlock);
    int a = 1;
    sleep(5);
    pthread_spin_unlock(spinlock);
   
    int count = 1;
    ;
  }

  return (void*)0 ;


}


void * thd_func1(void *arg){
 
  while(true){
    ThdArgs *args = (ThdArgs*)arg;
    pthread_spin_lock(&args->spinlock);

    if (10 == args->count){
      pthread_spin_unlock(&args->spinlock);
      return (void*)0;
    }
   
    cerr<<"Thread["<<pthread_self()<<"], count="<<args->count<<endl;
    args->count +=1 ;

    sleep(5);   

    if ( 10== args->count){
      pthread_spin_unlock(&args->spinlock);
      return (void*)1;
   
    }
    else
      pthread_spin_unlock(&args->spinlock);
  }

  return (void*)0 ;


}

int createBindThread(pthread_t *pthd, int cpuSeq, void * (*func)(void *), void *arg ){

  pthread_attr_t attr1;
  pthread_attr_init(&attr1);

  cpu_set_t cpuset;
  CPU_ZERO(&cpuset);
  CPU_SET(cpuSeq, &cpuset);


  if( pthread_attr_setaffinity_np(&attr1, sizeof(cpuset), &cpuset) ){
    cerr<<"setaffinity error "<<endl;
    return -1;

  }

  if ( pthread_create(pthd, &attr1, func, arg) ){
    cerr<<"pthread_create error "<<endl;
    return -1;
  }
  


  return 0;
}


int main(){

  int cpuCount = (int)sysconf(_SC_NPROCESSORS_ONLN);
  cout<<"cpu count="<<cpuCount<<endl;

  sched_param schedParam;
  schedParam.sched_priority = 1;

  if (sched_setscheduler(getpid(), SCHED_FIFO, &schedParam) == -1){
    cerr<<"sched_setscheduler error:"<<strerror(errno)<<endl;
  }

  pthread_t thd1, thd2;

  /*

  pthread_spinlock_t spinlock;
  pthread_spin_init(&spinlock, PTHREAD_PROCESS_PRIVATE);

  createBindThread(&thd1, 0, thd_func, (void*)&spinlock);
  createBindThread(&thd2, 1, thd_func, (void*)&spinlock);
  */

  ThdArgs args;
  args.count = 0;
  pthread_spin_init(&args.spinlock, PTHREAD_PROCESS_PRIVATE);
   
  createBindThread(&thd1, 0, thd_func1, (void*)&args);
  createBindThread(&thd2, 1, thd_func1, (void*)&args);

  /*
  while(true){
    int a = 1;
  }

  */

  void *rslt1 = NULL;
  void *rslt2 = NULL;

  pthread_join(thd1, &rslt1);
  pthread_join(thd2, &rslt2);

  cout<<"test over, thread["<<thd1<<"]  return"<<rslt1<<", thread["<<thd2<<"] return"<<rslt2<<endl;

  return 0;

}

原文地址:https://www.cnblogs.com/hugb/p/7401803.html