From b24b1e07d293ff3a82f1154948dc87615da7dc6f Mon Sep 17 00:00:00 2001
From: "dylan.frei" <dylan.frei@etu.hesge.ch>
Date: Sun, 26 Mar 2023 22:14:01 +0200
Subject: [PATCH] Added mutex for concurrency

---
 api.go | 21 ++++++++++++++++++---
 1 file changed, 18 insertions(+), 3 deletions(-)

diff --git a/api.go b/api.go
index 588dd8c..8cae4aa 100644
--- a/api.go
+++ b/api.go
@@ -18,9 +18,13 @@ import (
 	"path/filepath"
 	"strconv"
 	"strings"
+	"sync"
 	"syscall"
+	"time"
 )
 
+var m sync.Mutex
+
 func main() {
 
 	if _, err := os.Stat("/var/lib/image-viewer"); err != nil {
@@ -86,9 +90,9 @@ func Stop(c echo.Context) error {
 }
 
 func Upload(c echo.Context) error {
-	//-----------
-	// Read file
-	//-----------
+	//protect ressources
+	m.Lock()
+	defer m.Unlock()
 
 	// Source
 	file, err := c.FormFile("file")
@@ -139,6 +143,10 @@ func List(c echo.Context) error {
 }
 
 func Del(c echo.Context) error {
+	//protect ressources
+	m.Lock()
+	defer m.Unlock()
+
 	// Removing file from the directory
 	// Using Remove() function
 	img := c.Param("img")
@@ -150,6 +158,9 @@ func Del(c echo.Context) error {
 }
 
 func Display(c echo.Context) error {
+	//protect ressources
+	m.Lock()
+	defer m.Unlock()
 
 	//Check if program is running
 	if _, err := os.Stat("/var/run/image-viewer.pid"); err != nil {
@@ -187,6 +198,10 @@ func Display(c echo.Context) error {
 	}
 
 	syscall.Kill(pid, syscall.SIGUSR1)
+	//Ensure image has the time to be displayed before mutex release
+	//In case a subsequent call to display would be made before the signal is processed by the backend,
+	//the data from current.ppm could be corrupted (or too long) during process.
+	time.Sleep(500 * time.Millisecond)
 
 	return c.String(http.StatusOK, img+" is being displayed\n")
 }
-- 
GitLab