LoginSignup
6
4

More than 3 years have passed since last update.

C言語でa == 1 && a == 2 && a == 3をtrueにしてみたい

Last updated at Posted at 2018-01-21

C言語でもa == 1 && a == 2 && a == 3をtrueにしてみたい』の別アプローチ。
Core i7-5500U 2.40GHz + 16GB + Windows 10 + Cygwin64 の環境で gcc 6.4.0 を使用していますが環境に拠っては全然動かないかも。

hoge.c
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>

volatile int a = 1;

void* thread_func(void* vptr_args)
{
    (void)vptr_args;
    for (;;) {
        a = (a >= 3) ? 1 : a + 1;
    }
    return NULL;
}

int main(void)
{
    pthread_t thread;

    pthread_create(&thread, NULL, thread_func, NULL);
    for (;;) {
        if (a == 1 && a == 2 && a == 3) {
            printf("true\n");
            break;
        } else {
            printf("false\n");
        }
    }
    pthread_cancel(thread);
}
実行結果
$ gcc -O2 -Wall -Wextra hoge.c ; ./a|cat -n
     1  false
     2  false
     3  false
     4  false
     5  false
     6  false
     7  false
     8  false
     9  false
    10  false
    11  true

$

↑はたまたますごく早く終了した例。
wandboxで実行

6
4
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
4