socket_one_mutex

网络连接有两种,web式的http请求回复和游戏使用的tcp长连接,使用cocos2d开发即时交互式游戏肯定式使用tcp长连接,因为交互非常频繁,如果像web一样请求的话服务器处理握手都吃不消。网络交互多线程不分家,有网络就有多线程,这个是多线程的第一篇,互斥锁

多线程的原则是:不要同时访问共享资源

那么,这里有两个线程同时对一个变量+1,并打印。假设没有互斥锁

#include <stdio.h>

#include <pthread.h>

#include <unistd.h>

 

int buf = 0;

 

void* my_thread_call(void* arg)

{

  for(int i = 0; i < 10; i++)

  {

    d += 1;

    printf("%d\n", buf);

    sleep(1);

  }

  return NULL;

}

 

int main()

{

  pthread_t one_thread;

  pthread_t two_thread;

  pthread_create(&one_thread, NULL, my_thread_call, NULL);

  pthread_create(&two_thread, NULL, my_thread_call, NULL);

  pthread_join(one_thread, NULL);

  pthread_join(two_thread, NULL);

  return 0;

}

某次程序运行的结果是:

1

2

3

4

5

5

6

7

8

9

10

10

11

11

12

12

13

13

14

15

Program ended with exit code: 0

 

结果没有符合预期,正确的预期结果:buf因该为20,而且数字都是连续的。只有一个预期是对的,就是打印20次

所以说多个线程同时访问同一个共享资源会导致结果混乱,所以c语言引入了互斥锁的概念。

锁住资源,只能被当前线程使用,其他线程如果想使用被锁住的资源必须等待锁的打开

 

锁的使用分三部:创建锁,初始化锁,开关保护代码

加了互斥锁的代码:

 

#include <stdio.h>

#include <pthread.h>

#include <unistd.h>

 

int buf = 0;

//创建锁

pthread_mutex_t my_thread_lock;

 

void* my_thread_call(void* arg)

{

  for(int i = 0; i < 10; i++)

  {

    //上锁

    pthread_mutex_lock(&my_thread_lock);

    d += 1;

    printf("%d\n", buf);

    //解锁

    pthread_mutex_unlock(&my_thread_lock);

    sleep(1);

  }

  return NULL;

}

 

int main()

{

  //初始化锁

  pthread_mutex_init(&my_thread_lock, NULL);

 

  pthread_t one_thread;

  pthread_t two_thread;

  pthread_create(&one_thread, NULL, my_thread_call, NULL);

  pthread_create(&two_thread, NULL, my_thread_call, NULL);

  pthread_join(one_thread, NULL);

  pthread_join(two_thread, NULL);

  return 0;

}

运行结果:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

Program ended with exit code: 0

 

代码为macos xcode运行结果,win平台大同小异

 

posted @ 2017-05-17 14:57  小张学代码  阅读(151)  评论(0编辑  收藏  举报