天天看點

多線程的共享資源的解決方案

線程:是輕量級的程序,也是程式執行的最小機關。

線程的特點:共享程序的記憶體空間,對于作業系統而言,程序和線程都會參與系統的統一排程,同樣用task_struct來描述線程。

注意事項:由于多線程是通過第三方的線程庫來實作的,是以在LINUX 的gcc 編譯器下要這樣編譯,如要編譯thread1.c這個檔案,指令如下:gcc thread1.c -o thread1 -lpthread 後面-lpthread就是所要連結的第三方的線程庫。

下面是關于線程的一些函數

建立線程的函數

#include <pthread.h>//頭檔案
  int pthread_create(pthread_t *thread, const pthread_attr_t *at
tr,
void (*start_routine) (void *), void *arg);
           

函數參數:thread:建立的線程

attr 指定線程的屬性

arg 傳遞給線程執行的函數參數

routine:線程執行的函數

傳回值:成功0 失敗 -1

等待線程結束的函數

int pthread_join(pthread_t thread, void **retval);

線程退出函數原型

void pthread_exit(void *retval);

今天,我使用互斥鎖來保證共享資料的完整性,源代碼thread-unlock.c

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#define N 20
void *threadFunc(void *argc)
{
  char *p =(char *)argc;
  static char buf[N]={};

  int i=;
  while(*p!='\0')
  {
     buf[i]=*p;
     i++;
     p++;
     sleep();
  }
   puts(buf);
  pthread_exit(NULL);
}

int main()
{
    char str1[]="xldnzlh";
    char str2[]="6663217";
    //建立兩個線程
  pthread_t th1,th2;
  pthread_create(&th1,NULL,threadFunc,str1);
  pthread_create(&th2,NULL,threadFunc,str2);
//等待線程
 pthread_join(th1,NULL);
 pthread_join(th2,NULL);

  return ;
}
           

出現資源競争情況

多線程的共享資源的解決方案

但是加上互斥鎖之後就可以實作資源的完整性,一個線程執行完之後,另一個才可以執行. 源代碼 thread-lock.c 如下

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

#define N 20

pthread_mutex_t mutex;
void *threadFunc(void *argc)
{
  char *p =(char *)argc;
  static char buf[N]={};

  int i=;
  // 申請鎖
  pthread_mutex_lock(&mutex);
  while(*p!='\0')
  {
     buf[i]=*p;
     i++;
     p++;
     sleep();
  }
   puts(buf);
   //釋放鎖
  pthread_mutex_unlock(&mutex);

  pthread_exit(NULL);
}

int main()
{//初始化互斥鎖
    pthread_mutex_init(&mutex,NULL);
    char str1[]="xldnzlh";
    char str2[]="6663217";
        pthread_t th1,th2;
        pthread_create(&th1,NULL,threadFunc,str1);
        pthread_create(&th2,NULL,threadFunc,str2);

        pthread_join(th1,NULL);
        pthread_join(th2,NULL);
  return ;
}
           

測試結果如下

多線程的共享資源的解決方案

接着我們也可以使用一個信号量實作互斥鎖的功能。

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
#define N 20

sem_t sem1;
void *threadFunc(void *argc)
{
  char *p =(char *)argc;
  static char buf[N]={};

  int i=;
  // p操作
  sem_wait(&sem1);
  while(*p!='\0')
  {
     buf[i]=*p;
     i++;
     p++;
     sleep();
  }
   puts(buf);
   //v操作
  sem_post(&sem1);

  pthread_exit(NULL);
}

int main()
{
    //初始化一個信号量
    sem_init(&sem1,,);
    char str1[]="xldnzlh";
    char str2[]="6663217";
        pthread_t th1,th2;
        pthread_create(&th1,NULL,threadFunc,str1);
        pthread_create(&th2,NULL,threadFunc,str2);

        pthread_join(th1,NULL);
        pthread_join(th2,NULL);

  return ;
}
           

具體的測試結果如下所示:

多線程的共享資源的解決方案

以後會持續更新,寫的不好請大家見諒,關注我一下,一塊交流。

繼續閱讀