File: no_mutex.c

package info (click to toggle)
cbmc 6.6.0-4
  • links: PTS
  • area: main
  • in suites: forky, sid, trixie
  • size: 153,852 kB
  • sloc: cpp: 386,459; ansic: 114,466; java: 28,405; python: 6,003; yacc: 4,552; makefile: 4,041; lex: 2,487; xml: 2,388; sh: 2,050; perl: 557; pascal: 184; javascript: 163; ada: 36
file content (52 lines) | stat: -rw-r--r-- 1,325 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#include <assert.h>
#include <pthread.h>
#include <sched.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>

int shared_count = 0;

void *worker(void *arguments)
{
  for(int i = 0; i < 100; ++i)
  {
    int shared_count_copy = shared_count;
    // The following call to yield is here in order to increase the chance of
    // thread swaps during concrete execution in order to show unsoundness.
    sched_yield();
    ++shared_count_copy;
    shared_count = shared_count_copy;
  }
  pthread_exit(NULL);
}

pthread_t start_worker_thread(void)
{
  pthread_t worker_thread;
  const pthread_attr_t *const attributes = NULL;
  void *const worker_argument = NULL;
  const int create_status =
    pthread_create(&worker_thread, attributes, &worker, worker_argument);
  assert(create_status == 0);
  return worker_thread;
}

void join_thread(const pthread_t thread)
{
  const int join_status = pthread_join(thread, NULL);
  assert(join_status == 0);
}

int main(void)
{
  const pthread_t worker_thread1 = start_worker_thread();
  const pthread_t worker_thread2 = start_worker_thread();
  join_thread(worker_thread1);
  join_thread(worker_thread2);

  // Check if the shared count has been incremented 200 times.
  printf("The shared count is %d.\n", shared_count);
  assert(shared_count == 200);
  return EXIT_SUCCESS;
}