我有这个功能。
func (s *eS) Post(param *errorlogs.Q) (*errorlogs.Error, *errors.RestErr) {
//sub := q.Get("sub")
s.mu.Lock()
utime := int32(time.Now().Unix())
// Open our jsonFile
jsonFile, errFile := getlist(param.Id)
// if we os.Open returns an error then handle it
if errFile != nil {
return nil, errFile
}
jsonFile, err := os.Open(dir + "/File.json")
// if we os.Open returns an error then handle it
if err != nil {
return nil, errors.NewNotFoundError("Bad File request")
}
// read our opened jsonFile as a byte array.
byteValue, _ := ioutil.ReadAll(jsonFile)
// we initialize our model
var errorFile errorlogs.Error_File
// we unmarshal our byteArray which contains our
// jsonFile's content into '' which we defined above
json.Unmarshal(byteValue, &errorFile)
// defer the closing of our jsonFile so that we can parse it later on
defer jsonFile.Close()
// An object to copy the required data from the response
var id int32
if len(errorFile.Error) == 0 {
id = 0
} else {
id = errorFile.Error[len(errorFile.Error)-1].ID
}
newValue := &errorlogs.Error{
ID: id + 1,
Utime: utime,
}
errorFile.Error = append(errorFile.Error, *newValue)
file, err := json.Marshal(errorFile)
if err != nil {
return nil, errors.NewInternalServerError("Unable to json marshal file")
}
err = ioutil.WriteFile(dir+"/File.json", file, 0644)
if err != nil {
return nil, errors.NewInternalServerError("Unable to write file")
}
s.mu.Unlock()
return newValue, nil
}
在这里,我从并发请求中锁定此函数,如果某个客户端已经写入文件,则不会让另一个客户端同时写入该文件。但现在我感到困惑,这个互斥体是什么。Lock() 在锁定时对所有其他请求执行操作?它是否让其他客户端等待?还是只是忽略所有其他客户端?我们有什么办法用某种回应发回客户端吗?或者让另一个客户端等待,然后允许他们访问此功能?
人到中年有点甜
相关分类