Skip to content

Instantly share code, notes, and snippets.

@katsusuke
Last active June 1, 2025 09:09
Show Gist options
  • Select an option

  • Save katsusuke/6f7ebb9e8fb0acdcbb770cd4900d6f49 to your computer and use it in GitHub Desktop.

Select an option

Save katsusuke/6f7ebb9e8fb0acdcbb770cd4900d6f49 to your computer and use it in GitHub Desktop.
Thread sample
/thread_sample
*.o
# C言語プロジェクト用超便利Makefile 🔥
# コンパイラ設定
CC = gcc
# コンパイラフラグ
CFLAGS = -Wall -Wextra -O2
# デバッグ用フラグ
DEBUGFLAGS = -g -DDEBUG
# リンカフラグ
LDFLAGS =
# ライブラリフラグ(必要に応じて追加)
LIBS = -lm
# 実行ファイル名
TARGET = thread_sample
# ソースファイル
SRCS = $(wildcard *.c)
# オブジェクトファイル
OBJS = $(SRCS:.c=.o)
# デフォルトターゲット
all: $(TARGET)
# 実行ファイルの生成
$(TARGET): $(OBJS)
$(CC) -o $@ $^ $(LDFLAGS) $(LIBS)
@echo "✨ コンパイル完了!実行するには./$(TARGET)を入力してね ✨"
# オブジェクトファイルの生成
%.o: %.c
$(CC) $(CFLAGS) -c $< -o $@
# デバッグビルド
debug: CFLAGS += $(DEBUGFLAGS)
debug: clean all
@echo "🐞 デバッグモードでコンパイルしたよ!"
# クリーン
clean:
rm -f $(OBJS) $(TARGET)
@echo "🧹 掃除完了!"
# 実行
run: all
./$(TARGET)
@echo "🚀 実行完了!"
# ヘルプ
help:
@echo "使い方:"
@echo " make - プログラムをコンパイル"
@echo " make debug - デバッグ情報付きでコンパイル"
@echo " make clean - オブジェクトと実行ファイルを削除"
@echo " make run - コンパイルして実行"
@echo " make help - このヘルプを表示"
.PHONY: all debug clean run help
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
// 共有変数
int counter = 0;
const int LOOP_COUNT = 1000000;
// スレッド関数
void* increment_counter(void* arg) {
int thread_id = *(int*)arg;
printf("スレッド %d: 開始\n", thread_id);
for (int i = 0; i < LOOP_COUNT; i++) {
counter++; // カウンターをインクリメントするが、インクリメントはスレッドセーフではない
printf("スレッド %d: カウンター = %d\n", thread_id, counter);
}
printf("スレッド %d: 終了\n", thread_id);
return NULL;
}
int main() {
pthread_t thread1, thread2;
int id1 = 1, id2 = 2;
printf("開始: カウンター = %d\n", counter);
// 2つのスレッドを作成
pthread_create(&thread1, NULL, increment_counter, &id1);
pthread_create(&thread2, NULL, increment_counter, &id2);
// 両方のスレッドが終了するのを待つ
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
// 結果を表示
printf("終了: カウンター = %d\n", counter);
printf("期待される値は%dです\n", LOOP_COUNT * 2);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment